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.
class Team < ActiveRecord::Base
accepts_nested_attributes_for :interactions
class Interaction < ActiveRecord::Base
accepts_nested_attributes_for :players
team = Team.create(:name => "New York Lions", :interactions_attribues => [{
:players_attributes => [{:name => 'John Doe'}]}])
I've not checked the create so may have the arrays and hashes a little messed up but you get the idea. You need both the accepts_nested_attributes on the Team and the Interaction models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With