无法将本地对象传递给Rails 3中的嵌套部分 [英] Cant pass local object to nested partial in Rails 3
问题描述
_article.html.erb
<%if current_user.favorited?(article)%>
<%= render:partial => 'unfavorite',:object =>文章%>
<%else%>
<%= render:partial => 'favorite',:object =>文章%>
<%end%>
_favorite.html.erb(最喜欢和不喜欢的都差不多,所以我已经
<%= form_for current_user.favorites.find_by_article_id(article),:html => {:method => :delete,:class => 'unfavorite_form',},:remote => true do | f | %GT;
< div><%= f.hidden_field:article_id%>< / div>
<%= image_submit_tag(vote-favorite-on.png,:alt =>Favorite,:id =>favorites_button,:title =>从收藏夹中移除 >
<%end%>
错误讯息是:
<$ p $对于#<#< Class:0x491c2b0>:0x6727a58>的未定义局部变量或方法`article'
rails文档 rendering 提及这样的对象的使用:
<%= render:partial => customer,:object => @new_customer%>
然后说:
在客户部分内,客户变量将从父视图引用@ new_customer。
这使得它看起来像:object变量被翻译成部分的名称。所以在你的情况下,在_favorite中,你必须使用喜欢的变量:
<%= form_for current_user.favorites .find_by_article_id(favorite),:html => {:method => :delete,:class => 'unfavorite_form',},:remote => true do | f | %GT;
就我个人而言,我更喜欢本地语法,因为这样您就可以明确表示:
<%= render:partial => 'favorite',:locals => {:article =>文章}%>
Im hoping that someone can shed light on what is probably a simple mistake. Im trying to pass a local variable, article, which is in the partial _article.html.erb, to another partial nested within _article.html.erb. When the partial code is in _article.html.erb, it works fine.I've tried many variations (including :locals) but cant seem to pass the local variable.
_article.html.erb
<% if current_user.favorited?(article) %>
<%= render :partial => 'unfavorite', :object => article %>
<% else %>
<%= render :partial => 'favorite', :object => article %>
<% end %>
_favorite.html.erb (both favorite and unfavorite are more or less the same, so I've only posted one)
<%= 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 %>
The error message is:
undefined local variable or method `article' for #<#<Class:0x491c2b0>:0x6727a58>
The rails docs for rendering mention the use of object like this:
<%= render :partial => "customer", :object => @new_customer %>
And say that:
Within the customer partial, the customer variable will refer to @new_customer from the parent view.
Which makes it seem like the :object variable is translated into the name of the partial. So in your case, in _favorite, you'd have to use the favorite variable:
<%= form_for current_user.favorites.find_by_article_id(favorite), :html => { :method => :delete, :class => 'unfavorite_form', }, :remote => true do |f| %>
Personally I prefer the locals syntax, because then you can be explicit:
<%= render :partial => 'favorite', :locals => {:article => article} %>
这篇关于无法将本地对象传递给Rails 3中的嵌套部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!