ruby-on-rails Rails has_many:通过与acceptes_nested_attributes_for的关联

z9ju0rcb  于 2023-08-08  发布在  Ruby
关注(0)|答案(1)|浏览(122)

我正在努力使用acceptances_nested_attributes_for来实现多对多关联。我的报价可以有许多目录,一个目录可以添加到许多报价。模型:

class Offer < ApplicationRecord
  has_many :catalog_offer_memberships
  has_many :catalogs, through: :catalog_offer_memberships
  accepts_nested_attributes_for :catalog_offer_memberships
  accepts_nested_attributes_for :catalogs
end

class Catalog < ApplicationRecord
  has_many :catalog_offer_memberships
  has_many :offers, through: :catalog_offer_memberships
end

class CatalogOfferMembership < ApplicationRecord
  has_many :catalogs
  has_many :offers
  accepts_nested_attributes_for :catalogs
end

字符串
我希望在...

catalog = Catalog.create
Offer.create(catalogs_attributes:[{ id: catalog.id }])


Rails为我做了所有的工作,并创建了带有catalog_id和offer_id的CatalogOfferMembership。但我得到了:
`raise_nested_attributes_record_not_found!':无法找到ID=3的产品目录,用于ID=(ActiveRecord::RecordNotFound)``
我想,在“手动”创建设置之后:

offer = Offer.create
CatalogOfferMembership.create(offer_id: offer.id, catalog_id: catalog.id)


我可以使用以下操作报价的目录:

Offer.first.update(catalogs_attributes:[{id: catalog.id, _destroy: true}])


然后我没有得到错误,但CatalogOfferMembership仍然存在。
如何在创建或更新优惠本身的过程中更新优惠的目录列表?

xurqigkl

xurqigkl1#

不应该在嵌套属性中传递目录,而应该在关联中传递目录。

catalog = Catalog.create
Offer.create(catalogs: [catalog])

字符串
此外,CatalogOfferMembership应参考belongs_to的目录和报价。

class CatalogOfferMembership < ApplicationRecord
  belongs_to :catalog
  belongs_to :offer
end


说明:嵌套属性用于在创建时创建关联模型(这些模型没有ID)或更新已经关联模型的属性。在您的情况下,您可以通过以下方式简化呼叫:

# This creates an offer, a catalog and the association between them
Offer.create(catalogs_attributes: [{  }])


https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
关于删除CatalogOfferMembership,可以通过在产品和目录中设置has_many :catalog_offer_memberships上的dependent选项来实现。
https://guides.rubyonrails.org/association_basics.html#dependent

相关问题