Render partial :collection => @array specify variable name
I am rendering a partial like this:
$("#box_container").html("<%= escape_javascript( render :partial => 'contacts/contact_tile', :collection => @contacts) %>")
Problem is that my partial is expecting the variable 'contact'.
ActionView::Template::Error (undefined local variable or method `contact'
I simply want to tell the partial to expect a variable contact
. Should iterate through @contacts
as contact
. How do I do that?
Found this is also helpful from the docs. You aren't limited to having the variable named after the partial:
http://guides.rubyonrails.org/layouts_and_rendering.html
To use a custom local variable name within the partial, specify the :as option in the call to the partial:
<%= render :partial => "product", :collection => @products, :as => :item %>
With this change, you can access an instance of the @products collection as the item local variable within the partial."
The documentation at http://guides.rubyonrails.org/layouts_and_rendering.html says:
When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial.
So it will be passed a variable called "contact_tile" instead of "contact". Perhaps you can just rename your partial.
If this naming is important, you could do it explicitly without the collection option by something like:
@contacts.each { |contact| render :partial => 'contacts/contact_tile', :locals => {:contact => contact } }
(although as a commenter pointed out, this may not be as performant)
Latest syntax are :
index.html.erb
<%= render partial: "product", collection: @products %>
_product.html.erb
<p>Product Name: <%= product.name %></p>
@products
is used in partial as product
Where @products can be considered as Product.all
and product
can be considered as a row of product i.e. Product.first
as looped all product one by one.