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

后端 未结 3 843
自闭症患者
自闭症患者 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:13

    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/

提交回复
热议问题