文章模型有很多注释,评论属于文章。
以下是这篇文章的一部分。
<%= link_to article.title, article %>
<% if article.owned_by? current_user %>
<span class='actions'>
<%= link_to "Edit", edit_article_path(article) %>
<%= link_to "Delete", article, confirm: "Are you sure?", method: :delete %>
</span>
<% end %>
以下是部分评论的一部分。
<%= comment.name %> <<%= comment.email %>> commented:
<% if @article.owned_by? current_user %>
<span class="actions">
<%= link_to 'Delete', [@article, comment],
:confirm => 'Are you sure?', :method => :delete %>
</span>
<% end %>
您能告诉我为什么文章中使用article
,而注释部分中使用@article
吗?为什么不@article
在文章的部分?
如果我的问题对你来说太容易的话,我很抱歉,但我真的很困惑。
发布于 2015-11-26 15:02:23
检查您的代码,您可能在某个地方有这样的东西:
<%= render partial: '_some_partial.html.erb', locals: { article: @article }
正如MrYoshiji在注释中指出的那样,@article
是在控制器中设置的实例变量,而article
是该部分的局部变量。
在部分中只使用局部变量被认为是一个很好的实践,因为这样可以更容易地重用它们,包括在视图之间重用它们。
更新
如果在您的评论模型中碰巧有这样的内容:
class Comment < ActiveRecord::Base
belongs_to :article
end
然后,在注释部分中,可以使用:comment.article
代替实例变量和局部变量。
https://stackoverflow.com/questions/33941580
复制相似问题