我在 Rails 中使用 ActiveRecord 设置了多对多关联。假设表是
+------------+ +----------------+ +----------+
| categories | -- has many -= | category_items | =- has many -- | products |
+------------+ +----------------+ +----------+
在 category_items 表中,我有一组标准的 id 加上一个名为“type”的额外属性:
id:int
category_id:int
product_id:int
category_type:string
值得庆幸的是,Rails 提供了一些很好的 helper ,可以让映射表中的分配变得轻而易举。例如:
p = Product.first # p.id => 1
c = Category.first # c.id => 1
# now to make the assignment
p.categories << c
# or
p.categories.create(c)
这一切都很好,但假设我想用另一个表的类名自动更新“类型”字段。因此,对于上面给出的示例,我的 category_items 行将如下所示:
id = 1 (or some number)
category_id = 1
product_id = 1
category_type = nil
但我希望 category_type 等于“产品”。有没有办法让我建立一个回调或在关联中定义一些会自动设置 category_type 字段的东西?我知道在多态关联中,您可以使用 :source 或 :as 之类的东西来做这样的事情,但是多对多关联中的多态关联会引发错误。
有任何想法吗?
谢谢!
最佳答案
你有没有像这样在 category_items 上尝试过多态:
class CategoryItem < ActiveRecord::Base
belongs_to :category, :polymorphic => true
belongs_to :product
end
class ACategory < ActiveRecord::Base
has_many :category_items, :as => :category
end
class AnotherCategory < ActiveRecord::Base
has_many :category_items, :as => :category
end
class Product < ActiveRecord::Base
has_many :category_items
end
我认为这会奏效!
关于ruby-on-rails - 更新多对多关联中的映射表属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5670276/