While delving into ruby's nested models I encountered an issue.
Consider the following scenario,
I have the following models:
With the following specifications:
class Author < ActiveRecord::Base
attr_accessible :name
has_many :books, dependent: :destroy
accepts_nested_attributes_for :books #I read this is necessary here: http://stackoverflow.com/questions/12300619/models-and-nested-forms
# and some validations...
end
class Book < ActiveRecord::Base
attr_accessible :author_id, :name, :year
belongs_to :author
#and some more validations...
end
I would like to add a book to an author. Here is my authors_controller:
def new_book
@author = Author.find(params[:id])
end
def create_book
@author = Author.find(params[:id])
if @author.books.create(params[:book]).save
redirect_to action: :show
else
render :new_book
end
end
And this is the form with which I try doing it:
<h1>Add new book to <%= @author.name %>'s collection</h1>
<%= form_for @author, html: { class: "well" } do |f| %>
<%= fields_for :books do |b| %>
<%= b.label :name %>
<%= b.text_field :name %>
<br/>
<%= b.label :year %>
<%= b.number_field :year %>
<% end %>
<br/>
<%= f.submit "Submit", class: "btn btn-primary" %>
<%= f.button "Reset", type: :reset, class: "btn btn-danger" %>
<% end %>
When I type in the data and click "submit" it even redirects me to the correct author, but it doesn't save a new record for that author. 当我输入数据并单击“提交”时,它甚至会将我重定向到正确的作者,但不会为该作者保存新记录。 After a lot of research I can't seem to find what I am doing wrong here.
Change authors_controller to:
def new_book
@author = Author.find(params[:id])
@book = Book.new
end
Your form to:
<h1>Add new book to <%= @author.name %>'s collection</h1>
<%= form_for ([@author, @book]), html: { class: "well" } do |f| %>
And, routes.rb
resources :authors do
resources :books
end
You're missing a couple of things.
Controller:
...
def new_book
@author = Author.find(params[:id])
@author.books.build
end
...
View, it is f.fields_for
and not just fields_for
:
<%= f.fields_for :books do |b| %>
<%= b.label :name %>
<%= b.text_field :name %>
<br/>
<%= b.label :year %>
<%= b.number_field :year %>
<% end %>
You also need to add :nested_attributes_for_books
on your Author model accessible methods. The create method on you Author controller doesn't need any code additions to get going.
Note: You set the Books controller to render 'books#show' on success. If the app is redirecting you to the author that means the Author controller is handling the creation of the book, unless you set it to redirect to author and not the book.
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.