How can I use ActiveRecord's accepts_nested_attributes_for helper in a has_many :through association while adding attributes to the join table?
For example, say I've got a Team model:
class Team < ActiveRecord::Base
role = Role.find_by_name('player')
has_many :players,
:through => :interactions,
:source => :user,
:conditions => ["interactions.role_id = ?", role.id] do
class_eval do
define_method("<<") do |r|
Interaction.send(:with_scope, :create => {:role_id => role.id}) { self.concat r }
end
end
end
end
The team has_many players
through interactions
, because a user can occupy several roles (player, manager, etc.).
How can I use accepts_nested_attributes_for while at the same time adding attributes to the join table?
If I have an existing team record team
and an existing user record user
, I can do something like this:
team.players << user
team.players.size
=> 1
But if I create a new team with a nested player:
team = Team.create(:name => "New York Lions",
:players_attributes => [{:name => 'John Doe'}])
team.players.size
=> 0
In that last example, the team, user, and interaction records are created (and the team does have the user through interactions), but the interactions.role_id attribute isn't set here.