Rails form_with导致NoMethodError

时间:2017-09-26 16:08:36

标签: ruby-on-rails ruby forms

我从头开始重新构建博客,并且遇到了有关创建新文章的表单的问题。

<%= form_with scope: :article, url: articles_path, local: true do |form| %>会导致错误undefined method `form_with'

Rails提供以下建议: Did you mean? form_tag

尝试form_tag后,我收到以下错误:undefined method `label' for nil:NilClass

使用form_with

的新文章表单
<h1>New Blog Post</h1>
<%= form_with 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 %>

articles_controller.rb

class ArticlesController < ApplicationController
    def index
       @articles = Article.all 
    end

    def show
       @article = Article.find(params[:id]) 
    end

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)

        @article.save
        redirect_to @article
    end

    private
        def article_params
            params.require(:article).permit(:title, :text)
        end
end

当我将form_with更改为form_tag时,出现以下错误:undefined method `label' for nil:NilClass

为了记录,我使用

  1. Ruby 2.3.4
  2. Rails 4.2.5

1 个答案:

答案 0 :(得分:2)

您希望使用form_for @article do |form|form_for Documentation,当您需要不必附加到ActiveRecord对象的表单标记(HTML标记)时,会使用form_tag。< / p>