1

I have a User model and a Profile model. A User has_one Profile and a Profile belongs_to User.

From within app/views/users/show.html.erb, I would like to display the user's associated profile details.

I created a partial at app/views/profiles/shared/_show.html.erb. It contains:

<p>
  <strong>Title:</strong>
  <%= @profile.title %>
</p>

I am trying to include this partial from within app/views/users/show.html.erb like so (as recommended in the API documentation):

<%= render partial: 'profiles/shared/show', locals: { profile: @user.profile }%>

However, I keep getting the error:

undefined method `title' for nil:NilClass

If I remove the <%= @profile.title %> line from the partial, it renders correctly (so I assume the path is correct).

I have also checked that @user.profile contains a valid Profile object. It does.

What am I missing? How can I pass a variable to a partial which is shared with another controller?

2
  • 3
    try just profile.title Commented Oct 15, 2015 at 9:34
  • Aw man, you rock! That was it. If you add that as an answer, I'll accept it. Commented Oct 15, 2015 at 9:36

2 Answers 2

3

locals option in the render method, make a new variable with value from the hash locals: { foo: @bar }, instead of shared @ instance variable.

Sign up to request clarification or add additional context in comments.

Comments

3

just remove the @ from @profile.title as it is not a instance variable but a local variable so you don't need @

Note: do have a check in that partial for safety.

4 Comments

"Note: do have a check in that partial for safety." — Could you expand on that? What should I check?
you said its shared between controllers. so you'll have to be sure a profile is passed everytime to the partial. else the code'll break.
Sorry man, promised it to Зелёный before you replied (see comments).
@JackZelig No problem dude.. The important thing is that you got your answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.