Render partial :collection => @array specify variable name

Ruby on-Rails

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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."

Solution 2 - Ruby on-Rails

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)

Solution 3 - Ruby on-Rails

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.

Solution 4 - Ruby on-Rails

You can specify a custom variable name as the default with the keyword as:

<%= render partial: 'line_items/line_item', collection: order.line_items, as: :item %>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbotbotView Question on Stackoverflow
Solution 1 - Ruby on-RailsbotbotView Answer on Stackoverflow
Solution 2 - Ruby on-Railsmatthew.tuckView Answer on Stackoverflow
Solution 3 - Ruby on-RailsManish ShrivastavaView Answer on Stackoverflow
Solution 4 - Ruby on-RailsThomas Van HolderView Answer on Stackoverflow