我通过:collection选项将一个集合(@Feed_items)传递给_Feed_item部分.在_Feed_item部分内部,我想渲染另一个部分_like_button.在_like_button partial中,我希望能够访问集合的特定成员.我应该从_Feed_item部分传递到_like_button部分?
@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) %>
编辑
根据以下答案传递局部变量:
<%= render :partial => 'likes/like_button',:locals =>{:Feed_item => Feed_item} %>
然而,在提交之后,我得到一个ActionView :: Template :: Error(未定义的局部变量或方法’Feed_item’,当它试图通过ajax再次渲染表单时.如何通过ajax再次传递局部变量呼叫?
调节器
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>
解决方法
<%= render :partial => 'likes/like_button',:locals =>{:Feed_item => Feed_item} %>
Rails有一些很棒的文档http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables
在toggle.js中
$("#like").html("<%= escape_javascript(render :partial => 'likes/like_button',:locals =>{:Feed_item => @Feed}) %>");