ruby-on-rails – 更新多对多关联中的映射表属性
发布时间:2020-12-17 01:59:00 所属栏目:百科 来源:网络整理
导读:我在Rails中使用ActiveRecord进行了多对多的关联设置.我们说这些表是 +------------+ +----------------+ +----------+| categories | -- has many -= | category_items | =- has many -- | products | +------------+ +----------------+ +----------+ 在ca
我在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提供了一些很好的帮助,使得在映射表中进行赋值变得轻而易举.例如: 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) 这一切都很好,但是我想说我想用另一个表的类名自动更新“type”字段.因此,对于上面给出的示例,我的category_items行将如下所示: id = 1 (or some number) category_id = 1 product_id = 1 category_type = nil 但我希望category_type等于“Product”.有没有办法让我在关联中构建一个回调或定义一些会自动设置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 我认为这样就可以了! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |