Rails:是否可以向 has_and_belongs_to_many 关联添加额外的属性? [英] Rails: is it possible to add extra attribute to a has_and_belongs_to_many association?

查看:12
本文介绍了Rails:是否可以向 has_and_belongs_to_many 关联添加额外的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是如果我有两个模型,通过 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆