Ruby on Rails - Passing variables to a partial within a partial

diasks2 picture diasks2 · Sep 4, 2012 · Viewed 12.9k times · Source

I am passing a collection (@feed_items) to a _feed_item partial via the :collection option. Inside the _feed_item partial I want to render another partial _like_button. In the _like_button partial I want to be able to access a specific member of the collection. What should I be passing from the _feed_item partial to the _like_button partial?

 @feed_items = current_user.user_feed.order("id DESC").limit(5)

_feed.html.erb

 <%= render partial: 'shared/feed_item', collection: @feed_items %>

_feed_item.html.erb

 <%= render 'likes/like_button', ????? %>

_like_button.html.erb

 <% if like = current_user.likes.find_by_feed_id(feed_item.id) %>

EDIT

Passing the local variable as per the answers below worked:

 <%= render :partial => 'likes/like_button', :locals =>{:feed_item => feed_item} %>

However, after the like is submitted, I am getting a ActionView::Template::Error (undefined local variable or method 'feed_item' when it tries to render the form again through ajax. How can I pass the local variable again through the ajax call?

Controller

class LikesController < ApplicationController
  def create
    @like = Like.create(params[:like])
    @feed = @like.feed
    render :toggle
  end

  def destroy
    like = Like.find(params[:id]).destroy
    @feed = like.feed
    render :toggle
  end
end

toggle.js.erb

 $("#like").html("<%= escape_javascript render('like_button') %>");

_like_button.html.erb

 <% if like = current_user.likes.find_by_feed_id(feed_item.id) %>
  <%= form_for like, :html => { :method => :delete }, :remote => true do |f| %>
    <%= f.submit "Unlike" %>
  <% end %>
 <% else %>
  <%= form_for current_user.likes.build(:feed_id => feed_item.id), :remote => true do |f| %>
   <%= f.hidden_field :feed_id %>
   <%= f.hidden_field :user_id %>
   <%= f.submit "Like" %>
  <% end %>
 <% end %>

_feed_item.html.erb

    <div id="like">
      <%= render :partial => 'likes/like_button', :locals =>{:feed_item => feed_item} %>
    </div>

Answer

Pritesh Jain picture Pritesh Jain · Sep 4, 2012
 <%= render :partial => 'likes/like_button', :locals =>{:feed_item => feed_item} %>

Rails has got some awesome documention http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables

In toggle.js

 $("#like").html("<%= escape_javascript(render :partial => 'likes/like_button', :locals =>{:feed_item => @feed}) %>");