如何在 Rails 中使用多表继承为对象构建嵌套表单?我正在尝试使用与另一组具有多表继承功能的模型具有 has_many 关系的模型创建嵌套表单来创建对象。我使用formtastic和cocoon作为嵌套表单,并使用act_as_relation gem 来实现多表继承。
我有以下型号:
class Product < ActiveRecord::Base
acts_as_superclass
belongs_to :store
end
class Book < ActiveRecord::Base
acts_as :product, :as => :producible
end
class Pen < ActiveRecord::Base
acts_as :product, :as => :producible acts_as :product, :as => :producible
end
class Store < ActiveRecord::Base
has_many :products
accepts_nested_attributes_for :products, :allow_destroy => true, :reject_if => :all_blank
end'
对于此示例,该书与其他产品相比的唯一唯一属性是作者字段。实际上,我对 book 有许多独特的属性,这就是为什么我选择多表继承而不是更常见的单表继承的原因。
我正在尝试创建一个嵌套表单,允许您使用产品创建一个新商店。这是我的表格:
<%= semantic_form_for @store do |f| %>
<%= f.inputs do %>
<%= f.input :name %>
<h3>Books/h3>
<div id='books'>
<%= f.semantic_fields_for :books do |book| %>
<%= render 'book_fields', :f => book %>
<% end %>
<div class='links'>
<%= link_to_add_association 'add book', f, :books %>
</div>
<% end %>
<%= f.actions :submit %>
<% end %>
而 book_fields 部分:
<div class='nested-fields'>
<%= f.inputs do %>
<%= f.input :author %>
<%= link_to_remove_association "remove book", f %>
<% end %>
</div>
我收到此错误:
undefined method `new_record?' for nil:NilClass
在阅读了关于act_as_relation的 github 页面上的问题后,我想到了让 store 和 books 之间的关系更加明确:
class Product < ActiveRecord::Base
acts_as_superclass
belongs_to :store
has_one :book
accepts_nested_attributes_for :book, :allow_destroy => true, :reject_if => :all_blank
end
class Book < ActiveRecord::Base
belongs_to :store
acts_as :product, :as => :producible
end
class Store < ActiveRecord::Base
has_many :products
has_many :books, :through => :products
accepts_nested_attributes_for :products, :allow_destroy => true, :reject_if => :all_blank
accepts_nested_attributes_for :books, :allow_destroy => true, :reject_if => :all_blank
end
现在,我得到一个静默错误。我可以使用表单创建新的商店,并且 cocoon 允许我添加新的书籍字段,但是当我提交时,商店被创建但不是子书。当我通过“/books/new”路线时,我可以毫无问题地创建一个跨越(产品和书籍表)的新书籍记录。
这个问题有解决方法吗?其余的代码可以在这里找到。