ruby のネストされたモデルを掘り下げているときに、問題が発生しました。
次のシナリオを考えてみましょう。
私は次のモデルを持っています:
- 著者
- 本
以下の仕様:
著者:
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
著者に本を追加したいと思います。ここに私の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
そして、これは私がそれをやろうとするフォームです:
<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 %>
問題: データを入力して [送信] をクリックすると、正しい作成者にリダイレクトされますが、その作成者の新しいレコードは保存されません。多くの調査の後、ここで間違っていることを見つけることができないようです。