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

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

ruby on rails - has_many through additional attributes

How do we set additional parameters in has_many through associations?

Thanks. Neelesh

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...