Topic: has_many :through with attributes in join model

i have a  simple has_many through association between two models

 
class Participation < ActiveRecord::Base
  belongs_to :user
  belongs_to :contest
end
 
class User < ActiveRecord::Base
  has_many :participations
  has_many :contests, :through => :participations
end
 
class Contest < ActiveRecord::Base
  has_many :participations
  has_many :users, :through => :participations
end

The Join Model Participation has contest_id, user_id and an attribute called :style which is a string

I'd like to be able to set the attribute style whenever the association is automatically created using rails method below.

 @contest.users << @user 

but i have no clue how to set the :style attribute of participation.

Re: has_many :through with attributes in join model

Mind telling us what the :style attribute is?

- Ben

Re: has_many :through with attributes in join model

create_table "participations" do |t|
  t.column "user_id",         :integer
  t.column "contest_id",  :integer
  t.column "style",            :string
end

The style attribute is just a simple attribute that depends both on the user and the contest that is being entered. When a user registers for the contest they also input their preferred style.

I would just like to know how does one go about setting the attributes that are found in a join model and whether << can be used to achieve this.

Re: has_many :through with attributes in join model

Did you ever find a solution to this?

Re: has_many :through with attributes in join model

Doing

@contest.users << @user 

will just set contest_id and user_id values in Participations table. To set a style on a Participation model you should work from the Participation side, something like that (not so DRY, for your context, may be you'd find a better way):

@contest.users << @user 
participations = Participation.where(:contest => @contest, :user => @user)
participations.each do |participation|
  participation.style = "some style value"
  participation.save!
end