文章中的 NoMethodError#new in form_for 使用 Rails 4.2.5 教程

NoMethodError in Articles#new in form_for using Rails 4.2.5 tutorial

我正在尝试完成官方 Rails 教程和第 5.2 步。说明是做一个 form_with,但我得到了一个错误,查找了这个 Whosebug post: 。我将 form_with 更改为 form_for 就像答案所说的那样,但我收到此错误:

文章中没有方法错误#new

显示 /home/ubuntu/workspace/app/views/articles/new.html.erb 第 2 行出现的位置:

undefined method 'model_name' for {:scope=>:article, :url=>"/articles", :local=>true}:Hash

提取的源代码(第 2 行附近):

1. <h1>New Article</h1>
2. <%= form_for scope: :article, url: articles_path, local: true do |form| %>
3.   <p>
4.     <%= form.label :title %><br>
5.     <%= form.text_field :title %>
6.   </p>

Rails.root: /home/ubuntu/workspace

app/views/articles/new.html.erb:2:in '_app_views_articles_new_html_erb__1707235537542743350_40377020'

我正在使用 Cloud9,如果有帮助的话。这是我的视图和控制器代码:
查看:

<h1>New Article</h1>
<%= form_for scope: :article, url: articles_path, local: true do |form| %>
  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

控制器:

class ArticlesController < ApplicationController
  def new
  end

  def create
    render plain: params[:article].inspect
  end
end

您可能 运行正在使用旧版本的 Rails。在命令行 运行 rails -v 并确保它与您正在阅读的教程的版本相同。

我原以为你的 ArticleController 会是这样的:

class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end

  def create
    render plain: params[:article].inspect
  end
end

您的视图如下所示:

<h1>New Article</h1>
<%= form_for @article do |form| %>
  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

给定 @articleform_for 将正确推断 url,只要:

the record passed to form_for is a resource, i.e. it corresponds to a set of RESTful routes, e.g. defined using the resources method in config/routes.rb

根据 docs.

也许还值得注意的是,form_for 的签名是(同样,根据文档):

form_for(record, options = {}, &block)

这意味着 form_for 期望传递 (1) 一条记录,(2) 零个或多个选项,以及 (3) 一个块。如文档中所述,'record' 实际上可以是许多事物之一(例如实例、字符串或符号)。

当你这样做时:

<%= form_for scope: :article, url: articles_path, local: true do |form| %>

我相信发生的事情是 form_for 正在接受散列 {scope: :article, url: articles_path, local: true} 作为记录,并试图通过对散列调用 model_name 来推断 url .哈希自然不会响应 model_name,因此您得到:

undefined method 'model_name' for {:scope=>:article, :url=>"/articles", :local=>true}:Hash