简体   繁体   中英

How to debug undefined method form_with error

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

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 %>

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| %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM