Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do we set additional parameters in has_many through associations?

Thanks. Neelesh

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
722 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...