确定...上面edgeguides码 - 困惑特定错误
<%= form_for :article, url: articles_path do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
好吧,代码为http://edgeguides.rubyonrails.org/getting_started.html
的问题涉及到这部分:
<%= form_for :article, url: articles_path do |f| %>
<% if @article.errors.any? %>
如果我改变:article
到@article
在第一行,它仍然有效。它应该,因为它们可以互换,是的?
但是,如果我改变了第二个这样的:
@article.errors.any?
到:article.errors.any?
它产生的错误,特别是这样的:
undefined method 'errors' for :article:Symbol
为什么?
请保持温柔,因为我仍然在试图弄清楚看起来很明显的东西。
在这里大声思索,为什么符号不能用于第二行是因为它需要一个实例来收集错误,对吗?
但是,是不是符号可以与实例互换?这意味着Rails应该读取该行并将其转换为实例,即它找到模型类的实例,是的?
编辑
显然,我没看过远远不够了,我可没有采取心脏是我以前的form_for帮手了...
EdgeGuides代码后说,这:
The first parameter of the form_tag can be an object, say, @article which would cause the helper to fill in the form with the fields of the object. Passing in a symbol (:article) with the same name as the instance variable (@article) also automagically leads to the same behavior. This is what is happening here. More details can be found in form_for documentation.
的关键是的form_for帮手。
这就是为什么它不适用于第二行...因为它无法弄清楚如何填写符号的位置。
希望这可以帮助一些其他可怜的家伙/女孩。
ps。随时纠正我,如果我的编辑是错误的。
你有没有得到你的问题的答案仍然有一些疑问? –