在深入研究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 %>
问题: 当我在数据类型,然后单击“提交”它甚至会将我重定向到正确的作者,但它不会为该作者保存新的记录。 经过大量的研究,我似乎无法找到我在这里做错了什么。
显然,改变了我的路由机制......现在它给了我'未定义的方法\'author_books_path''并引用表格的第二行... – weltschmerz
请参阅http://blog.dominicsayers.com/2011/08/24/howto-create-a-simple -parent-child-form-in-rails-3-1 /从头开始具有子窗体实现。 –
太棒了,谢谢!该链接解决了它:-) – weltschmerz