Mel Mel - 1 month ago 9
Ruby Question

Rails 5 - Helper methods

I am trying to learn how to use helper methods in my Rails 5 app.

I have a model called

Proposal
and another called
User
.

In my
Proposal
helper, I'm trying to write a helper to show the name and location of the parent user (proposals belong to users).

I have tried:

def text_for_proponent(proposal, user)
return unless current_user.id == proposal.user.id
render 'users/profiles/formal_name_title', user: @proposal.user
end


Then in my views/users/formal_name_title.html.erb, I have:

<%= @user.full_name.titleize %> · <%= @user.organisation.title.titleize %> · <%#= @user.addresses.first.country_name.titleize %>


Then in my proposals/show.html.erb, I have:

<h4><%= text_for_proponent(@proposal, @proposal.user) %></h4>


This isn't working. I can't find how to give the user instance to the helper to be used in populating the view.

Can anyone see where I'm going wrong?

Answer

The problem is that you're trying to access @proposal.user but @proposal is nil inside the helper. You should use the local variable proposal instead.

render 'users/profiles/formal_name_title', user: proposal.user

And, you should change your partial to use the local variable user.

<%= user.full_name.titleize %> · <%= user.organisation.title.titleize %> · <%= user.addresses.first.country_name.titleize %>