has_many through additional attributes

后端 未结 4 724
温柔的废话
温柔的废话 2020-12-15 08:48

How do we set additional parameters in has_many through associations?

Thanks. Neelesh

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 09:01

    This blog post has the perfect solution: http://www.tweetegy.com/2011/02/setting-join-table-attribute-has_many-through-association-in-rails-activerecord/

    That solution is: create your ":through model" manually, rather than through the automated way when you append to its owner's array.

    Using the example from that blog post. Where your models are:

    class Product < ActiveRecord::Base
      has_many :collaborators
      has_many :users, :through => :collaborators
    end
    
    class User < ActiveRecord::Base
      has_many :collaborators
      has_many :products, :through => :collaborators
    end
    
    class Collaborator < ActiveRecord::Base
      belongs_to :product
      belongs_to :user
    end
    

    Previously you may have gone: product.collaborators << current_user.

    However, to set the additional argument (in this example is_admin), rather than the automated way of appending to the array, you can do it manually like:

    product.save && product.collaborators.create(:user => current_user, :is_admin => true)

    This approach allows you to set the additional arguments at save-time. NB. the product.save is necessary if the model hasn't yet been saved, otherwise it can be omitted.

提交回复
热议问题