Rails:是否可以为has_and_belongs_to_many关联添加额外的属性? [英] Rails: is it possible to add extra attribute to a has_and_belongs_to_many association?
问题描述
我的意思是,如果我有两个通过has_and_belongs_to_many关联进行连接的模型,我可以在每个关联的联接表中存储其他数据吗?也就是说,多余的数据将不会是任何一个表中的单个记录的一部分,而是它们之间的连接.
What I mean is if I have two models, connected by a has_and_belongs_to_many association, can I store other data in the join table for each association? That is, the extra data would not be part of a single record in either table, but instead of the connection between them.
我的实际模型如下:
class Part < ActiveRecord::Base
has_and_belongs_to_many :assemblies
has_and_belongs_to_many :packages
belongs_to :user
validates :name, :user_id, :presence => true
end
class Package < ActiveRecord::Base
has_and_belongs_to_many :parts
belongs_to :user
end
因此,重点是每个部分都有许多包装,并且每个包装都有不同的零件.我要添加的是数量.那不是每个零件的数量,而是每个零件的每个包装的数量.
So the point is that each part is available in many packages, and each package has different parts. What I want to add is a quantity. That would not be quantity of each part, but of each package of each part.
我在ActiveRecord中找不到如何执行此操作.如果我不使用rails/activerecord,则只需在联接表中添加一个数量列即可将零件与包装相关联.我显然可以在迁移中进行此更改,但是如何使用ActiveRecord访问值?
I can't find how to do this in ActiveRecord. If I was not using rails/activerecord, I'd just add a quantity column to the join table which relates parts to packages. I could obviously make this change in a migration, but how would I access the value using ActiveRecord?
推荐答案
简短回答否,您不能拥有HABTM关系.它仅适用于简单的多对多关系.
Short answer no you cannot with a HABTM relationship. It is only intended for simple many to many relationships.
您将需要使用has_many:through关系.在这种情况下,您将创建一个联接模型(PartPackage),您可以在其中定义所需的额外属性.
You will need to use a has_many :through relationship. In this scenario you will create a join model (PartPackage) where you can define the extra attributes that you need.
class Part < ActiveRecord::Base
has_many :part_packages
has_many :packages, :through => :part_packages
has_and_belongs_to_many :assemblies
belongs_to :user
validates :name, :user_id, :presence => true
end
class PartPackage < ActiveRecord::Base
belongs_to :part
belongs_to :package
end
class Package < ActiveRecord::Base
has_many :part_packages
has_many :parts, :through => :part_packages
belongs_to :user
end
这篇关于Rails:是否可以为has_and_belongs_to_many关联添加额外的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!