我希望有人能够阐明可能是一个简单的错误。我试图将局部变量article(位于部分_article.html.erb 中)传递给嵌套在_article.html.erb 中的另一个部分。当部分代码位于_article.html.erb中时,它工作正常。我尝试了很多变体(包括:locals),但似乎无法传递局部变量。
_article.html.erb
<% if current_user.favorited?(article) %>
<%= render :partial => 'unfavorite', :object => article %>
<% else %>
<%= render :partial => 'favorite', :object => article %>
<% end %>
_favorite.html.erb(最喜欢的和最不喜欢的都或多或少相同,所以我只发布了一个)
<%= form_for current_user.favorites.find_by_article_id(article), :html => { :method => :delete, :class => 'unfavorite_form', }, :remote => true do |f| %>
<div><%= f.hidden_field :article_id %></div>
<%= image_submit_tag("vote-favorite-on.png", :alt => "Favorite", :id => "favorites_button", :title => "Remove from favorites") %>
<% end %>
错误信息是:
undefined local variable or method `article' for #<#<Class:0x491c2b0>:0x6727a58>
最佳答案
rendering 的 Rails 文档像这样提及对象的使用:
<%= render :partial => "customer", :object => @new_customer %>
并说:
Within the customer partial, the customer variable will refer to @new_customer from the parent view.
这使得 :object 变量看起来像是被翻译成部分的名称。因此,在您的情况下,在 _favorite 中,您必须使用 最喜欢的变量:
<%= form_for current_user.favorites.find_by_article_id(favorite), :html => { :method => :delete, :class => 'unfavorite_form', }, :remote => true do |f| %>
我个人更喜欢本地语法,因为这样你就可以明确:
<%= render :partial => 'favorite', :locals => {:article => article} %>
关于ruby-on-rails - 无法将本地对象传递给 Rails 3 中的嵌套部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9731318/