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

后端 未结 3 732
自闭症患者
自闭症患者 2021-02-04 02:37

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 w

3条回答
  •  借酒劲吻你
    2021-02-04 03:19

    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
    

提交回复
热议问题