2017-09-26 40 views
0

我正在從頭開始重新構建博客,並且遇到了有關創建新文章的表單的問題。Rails form_with NoMethodError中的結果

<%= 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_withform_tag我得到以下錯誤:undefined method `label' for nil:NilClass

爲了記錄在案,我使用

  1. 紅寶石2.3.4
  2. 的Rails 4.2.5
+1

Form_with已經在rails 5(5.1?)中引入,使用form_for在rails 4中使用正確的語法。 – Syl

+0

感謝您的建議! – Michael

回答

2

您想使用form_for @article do |form|form_for Documentation,form_tag用於當您想要af orm標籤(HTML標籤)不一定附加到ActiveRecord對象。

+0

非常感謝!它像一個魅力一樣工作! – Michael