6

I'm getting the error:

undefined form_with for #<#<Class:0x7ac62e0>:0x551e5a8> in articles#new

The error occurs in the following file: new.html.erb Which has:

<%= form_with(model: [@article] , local: true) do |f| %>
  <p>
    <%= f.label :title %><enter code here`br>
    <%= f.text_field :title %>
  </p>

And the controller articles_controller.rb has:

class ArticlesController < ApplicationController
  def new
  end
end
2
  • 1
    I get the same problem. Funny cos I'm following the RoR tutorial in guides.rubyonrails.org/getting_started.html#creating-articles !! Rails version is 5.0.6, Ruby is 2.3.1 Commented Feb 7, 2018 at 8:36
  • 2
    For anyone else who has followed that tutorial and had this problem - upgrade Rails to a version 5.1 or greater and it will solve the issue with form_with. More info m.patrikonrails.com/… Commented Jun 26, 2018 at 16:35

2 Answers 2

4

your controller just has new command see sample below for create instance variable @article

articles_controller.rb

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

new.html.erb

<%= form_with @article do |f| %>
  <%= f.label "Enter title: " %> 
  <%= f.text_field :title %> 
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

0

I've seen this error while working on nested routes. It occurred when the controller routes are defined as nested under another controller's route.

For example:

resources :authors do 
   resource :books, only: [index, :new]
end

it will create following routes:

/authors/author_id/books/:id
/authors/author_id/books/new 

The method form_with try to execute the method book_path. But it is defined as author_books_path.

I found the solution by adding extra resources :books outside of the resources :books block.


resources :books

resources :authors do 
   resource :books, only: [:index, :new]
end

Edit: This solution will build the form without error but action URL won't be be correct because it will use books/.. instead of author/:author_id/books. That's why it is better use form_for instead of form_with while working on nested routes by passing parent and child model in a array.

<% form_for [@author, @book] do |form| %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.