我将通过 :collection 选项向 _feed_item 部分传递一个集合 (@feed_items)。在 _feed_item 部分内,我想要呈现另一个部分 _like_button。在 _like_button 部分中,我想要能够访问集合的特定成员。请问我需要从 _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} %>
然而,当我提交赞时,它尝试通过 ajax 再次渲染表单时,出现了 ActionView::Template::Error (undefined local variable or method 'feed_item'
的错误。我该如何再次通过 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>
ActionView::Template::Error (undefined local variable or method 'feed_item' for #<#<Class:0x00000102f6b078>:0x0000010452f7d8>)
。你有什么想法是什么原因导致的吗? - diasks2$("#like").html("<%= escape_javascript render('like_button') %>");
- diasks2