Michael Michael - 21 days ago 11
Ruby Question

Rails form_with results in a NoMethodError

I'm re-building a blog from the ground up and a ran into a problem concerning the form for creating new articles.

<%= form_with scope: :article, url: articles_path, local: true do |form| %>
results in the error
undefined method `form_with'
.

Rails provides the following suggestion:
Did you mean? form_tag


Upon trying
form_tag
, I get the following error:
undefined method `label' for nil:NilClass


Form for new article using 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


When I change
form_with
to
form_tag
I get the following error:
undefined method `label' for nil:NilClass


For the record, I'm using


  1. Ruby 2.3.4

  2. Rails 4.2.5


Answer Source

You want to use form_for @article do |form| (form_for Documentation, form_tag is used when you want a form tag (HTML tag) that's not necessarily attached to a ActiveRecord object.