Passing parameters to partial view
I have a view that displays multiple images and those images' associated tags. I decided to use a partial view for each image and its tags, but I am having trouble passing in the image object into the partial view. Here is the main view's relevant code:
<table>
<% @images.each do |i| %>
<tr>
<%= render :partial => :image_tag, :image => i %>
</tr>
<% end %>
</table>
Here is the partial view's relevant code (partial view is named _image_tag.html.erb):
<table>
<%= image.id %>
<%= image_tag image.src %>
</table>
I read in this thread that I can pass in the image object the way that I am currently doing it. I tried passing in the id through an options hash on the render method, and that also didn't work. The error I am getting is:
undefined method `model_name' for Symbol:Class
centered around the line where I am calling render :partial in the main view.
<%= render partial: "image_tag", locals: {image: i} %>
is how you would pass variables to partials.
Something else to consider for those that may be having trouble sending value(s) to a partial. If you omit the 'partial:' before your partial path, like so...:
<%= render 'my_partial', :locals => {:greeting => 'Hello world', :x => 36} %>
...it seems you'll be unable to access the locals hash values directly. Rather, you would need to do the following:
<div>
<h1> <%= locals[:greeting] %> , my x value is <%= locals[:x] %> </h1>
</div>
However, including 'partial:' before your partial path, like the following...:
<%= render partial: 'my_partial', :locals => {:greeting => 'Hello world', :x => 36} %>
...allows you to directly access the hash values, like so:
<div>
<h1> <%= greeting %> , my x value is <%= x %> </h1>
</div>
Just something to consider, I was getting tripped up by this issue when trying to access the locals hash values and realized I had omitted the 'partial:' component.
You can also pass the whole object to a partial like this:
<%= render :partial => "partialpath", :object => :image %>
You would replace i with image in your case and partial path with whatever your partial is called. Inside the partial it would have access to a local variable with the same name as the partials name. So if your partials name is "image" the local variable image will be the object you pass in.
EDIT: Looking at the rails guides looks like in rails 3 the :object is now accessed as an instance variable instead of a local so @image would be what you use in the partial.