How to use a partial layout with a collection? Rails
I am calling:
render @users, :layout => "homepage"
because I want to wrap the default partial for users (views/_us开发者_运维问答er.html.erb) with a custom layout just for the homepage (views/users/_homepage.html.erb).
but, when I do this, I get the NoMethodError on the user.name method.
For some reason it seems like the user variable is not getting initialized properly inside the user partial.
It turns out after some test, the homepage partial is not even getting called, it is going straight to the user partial ....
This is not the solution I wanted, I believe there may actually be a way to make this work using just a call to render, but this is what gave me the correct output:
@users.each do |user|
render :partial => "users/user",
:layout => "users/homepage",
:locals => { :user => user }
end
Or is it that the :layout option only works when rendering a single resource and not a collection?
As of Sept. 2019, in Rails 6, this is how we are doing this:
<%= render partial: 'homepage_user_list_entry', collection: @users %>
With alias:
<%= render partial: 'homepage_user_list_entry', collection: @banned_users, as: :user %>
Hope this helps future searchers, and also me in the future.
Try adding :as => :user
to render a partial from a view:
<%= render :collection => @users, :as => :user, :partial => 'users/user_short_form', %>
You should do something like
<%= render 'homepage', :collection => @users, :layout => 'homepage' %>
not sure about the :layout option, but you have to pass @users thro :collection
hope it helps!
Not sure if this is a newer addition to Rails, but in Rails 4.2.1 I can pass my collection to the partial
argument of render
:
render partial: @users, layout: "homepage"
精彩评论