具有预填充数据的嵌套表单

时间:2016-07-01 10:34:27

标签: ruby-on-rails activerecord simple-form

我在管理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

0 个答案:

没有答案