Rails: is it possible to add extra attribute to a has_and_belongs_to_many association?

萝らか妹 提交于 2019-12-03 00:12:11

Short answer no you cannot with a HABTM relationship. It is only intended for simple many to many relationships.

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

There is a key difference between has_many :through and has_and_belongs_to_many the Rails guide explains the differences between the two options in greater detail, however if you want to add data that describes the relationship then use has_many :through and you can access the model that joins the two.

This is what has_many :through looks like:

Actually, this is possible.

1) Add a quantity key to the packages_parts join table

2) Add this to your Part model

has_and_belongs_to_many :packages, -> { select("packages.*, 
packages_parts.quantity") }

Now you can do part.packages[0].quantity, for example.

What this does is tell Rails to fetch the quantity key whenever it gets the packages for a specific part.

(You can do the same for your Package model if you want to do package.parts.first.quantity as well - just put this on the Package model also, replacing 'packages' with 'parts')

More info: https://ducktypelabs.com/using-scope-with-associations/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!