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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Ruby on Rails – 将变量传递给部分内部的部分前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我通过: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}) %>");
原文链接:https://www.f2er.com/ruby/270166.html

猜你在找的Ruby相关文章