2014-02-18 21 views
0

确定...上面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。随时纠正我,如果我的编辑是错误的。

+0

你有没有得到你的问题的答案仍然有一些疑问? –

回答

0
:article is only the model (not really sure :) 
@article is an instance with data in it 
    when Article.new empty, Article.find(..) with data 

在我的应用我总是使用

<%= form_for @article do |f| %> 

我肯定的形式和歼变量反映的实例@article 如预期的所有字段将被填补。

在更复杂的路线中,我也使用了url参数。

<%= form_for :article, :url => articles_path do |f| %> 

但它只是更清楚,如果它走向方向嵌套路线。

0

尽管form_for:article和form_for @article都可以工作,但这只意味着form_for方法可以从@article或:article收集所需的信息。这并不意味着符号和实例是可以互换的。