2

Specifically, on an index page, you might have

@users.each do |user|
 render 'layouts/shortprofile'
end

where short profile contains data from the user and other related models.

The partial is trying to read from the index method in the user model, but there is no variable defined in that method for an individual user. It feels like the |user| block var should read into the partial, but it doesn't seem to.

For example, in the partial I might want to have something like -

user.blogs[1..3].each do |blog|
  blog.title
  blog.created_at
  .....

... but I don't know how to get the user value into the partial.

I want to keep it as a partial cos it's displayed in several contexts and I want to be DRY.

2 Answers 2

3

Pass it to your partial using the local variable, and make sure you explicitly specify partial:

e.g/

@users.each do |user|
 render partial: 'layouts/shortprofile', locals: { user: user }
end

More info here: http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables

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

2 Comments

Hi gef - thanks for this - I've tried it but have screwed it up somehow - I've updated the question in response, and am reading the docs. cheers, Dan
Hey @RADan you need to include partial: when passing additional options. I've just updated the answer to show :)
0

You could change your partial to "_user.html.erb" and move it to the "views/users" folder with your index view, and replace the @users.each block with this:

<%= render @users %>

...which should successfully pass each user object to the user variable in the partial.

Comments

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.