我希望有人可以阐明可能是一个简单的错误。我试图将部分_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>
答案 0 :(得分:2)
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变量被转换为partial的名称。所以在你的情况下,在_favorite中,你必须使用最喜欢的变量:
<%= form_for current_user.favorites.find_by_article_id(favorite), :html => { :method => :delete, :class => 'unfavorite_form', }, :remote => true do |f| %>
我个人更喜欢locals语法,因为那时你可以是显式的:
<%= render :partial => 'favorite', :locals => {:article => article} %>