Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accepts_nested_attributes_for through join table with attributes on the join

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.

like image 743
trisignia Avatar asked Nov 05 '22 08:11

trisignia


1 Answers

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.

like image 195
james2m Avatar answered Nov 09 '22 03:11

james2m