Rails ActiveRecord has_many 与相同模型的关联

问题描述 投票:0回答:1

我正在努力在现有站点中实施产品捆绑包。我有一个

Product
模型,在枚举中包含各种产品类型,我在其中添加了“捆绑包”产品类型。

我希望能够创建一个具有product_type 捆绑包的产品,其中将包含多个其他类型的产品。例如,一个捆绑包可能包含多本书。

我有一个

BundleProduct
模型和数据库表用于存储关联,仅包含以下内容:

class BundleProduct < ApplicationRecord 
    belongs_to :bundle,  :class_name => 'Product', :foreign_key => 'bundle_id'
    belongs_to :product, :class_name => 'Product', :foreign_key => 'product_id'
end

这是我的

Product
模型中的相关代码,对此示例进行了一些简化:

class Product < ApplicationRecord
    enum :product_type => { :book => 1, :supplies => 2, :bundle => 3 } 
    has_many :bundle_products, :foreign_key => :bundle_id, :dependent => :destroy
end

在 Rails 控制台中,我可以运行

product.bundle_products
来获取一个空数组,如果我直接在
bundle_products
表中创建记录,则对象会正确显示。

但是,当我尝试通过 Rails 应用程序保存记录时,出现

RecordNotFound
异常。我使用的表单是捆绑产品的一个非常基本的编辑表单,其中包含一个复选框列表,用于选择要包含在捆绑中的其他产品。

ActiveRecord::RecordNotFound: Couldn't find all BundleProducts with 'id': (309, 12, 225)
(found 0 results, but was looking for 3). Couldn't find BundleProducts with ids 309, 12, 225.

我的表单针对这些关联记录提交的参数就是这样(不相关的属性省略):

{"product"=>{"bundle_product_ids"=>["309", "12", "225"]}}

我的控制器只是在保存父记录时调用

product.update!(product_params)
,为了排除故障,我通过
params.require(:product).permit!
明确允许了所有参数。

ActiveRecord 正在寻找具有这些 ID 的 BundleProducts,而它应该寻找产品。我的直觉是,我对这种关系的思考完全错误,但我一直无法在这里找到类似的问题。

我做错了什么?我是否只是错过了一步,或者我的方法对于我想做的事情完全错误?

我正在使用 MariaDB 运行 Rails 6.1。

ruby-on-rails activerecord
1个回答
0
投票

所以是的,

bundle_product_ids
是关联的
BundleProduct
ID 的名称。您需要像
:through
这样的
has_many :bundled_products, through: :bundle_products, class_name: "Product"
关联(您可能也需要
:source
)。然后你就可以拥有
bundled_product_ids

© www.soinside.com 2019 - 2024. All rights reserved.