gpt4 book ai didi

ruby-on-rails - Ruby on Rails - 将变量传递给部分中的部分

转载 作者:数据小太阳 更新时间:2023-10-29 06:53:51 25 4
gpt4 key购买 nike

我正在通过 :collection 选项将集合 (@feed_items) 传递给 _feed_item 部分。在 _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 调用再次传递局部变量吗?

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>

最佳答案

 <%= 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}) %>");

关于ruby-on-rails - Ruby on Rails - 将变量传递给部分中的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com