Search code examples
ruby-on-railsrubyrenderpartial

How can I access other elements of a Collection when doing render: collection?


I am rendering a collection of objects, and, within the partial for each object that I render, I want to be able to output some info that requires a reference to an item in the collection I have yet to iterate over:

users_controller.rb:

def index
  @users = %w(Nelson Lisa Milhouse Janey)
end

index.html.haml:

= render :partial => "user", :collection => @users

_user.html.haml:

- if next_user
  %p= "#{next_user} likes #{user}!"
- else
  %strong NOBODY LIKES MILHOUSE

Is there an inherent accessor I don't know about, which I would substitute for "next_user", and call within the partial to get data on any of the other objects in the collection?

Or would I be doomed to passing "next_user" in as a local variable?


Solution

  • It can be done like this:

    = render :partial => "user", :collection => @users, :locals => { :users => @users}
    

    You will then have access to @users.