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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…