我在管理has_many时遇到问题:通过嵌套表单进行关联
创建产品时,我想显示标签表中的所有标签 并在product_tags表中创建一条带有一些额外信息的新记录
这可能是感谢你的帮助
模型
class Product < ApplicationRecord
has_many :product_tags
has_many :tags, through: :product_tags
accepts_nested_attributes_for :product_tags, :reject_if => :all_blank, :allow_destroy => true
end
class ProductTag < ApplicationRecord
belongs_to :product
belongs_to :tag
end
class Tag < ApplicationRecord
has_many :product_tags
has_many :products, through: :product_tags
end
View
= simple_form_for @product do |f|
= f.input :name
= f.input :price
= f.fields_for :tags do |tag|
b tag.object.name
= tag.fields_for :product_tags do |product_tag|
= product_tag.input :tag_id, as: :hidden, input_html{value:tag.object.id}
= product_tag.input :priority
= product_tag.input :status