Tyler DeWitt
Tyler DeWitt

Reputation: 23576

Using build does not create join model on has_many :through association

My 2 models:

Class TeamHistory < ActiveRecord::Base
  has_many :player_to_team_histories
  has_many :players, through: :player_to_team_histories

  belongs_to :team
end

Class Player < ActiveRecord::Base
  has_many :player_to_team_histories
  has_many :team_histories, through: :player_to_team_histories
end

I can't get the player_to_team_histories to be created using @team_history.players.build, but it works fine with @team_history.players.create

>>team = Team.create
>>team_history = team.team_histories.create
>>player = team_history.players.create
>>player.team_histories.count
1
>>player2 = team_history.players.build
>>player2.team_histories.count
0
>>player2.save
>>player2.team_histories.count
0

Upvotes: 1

Views: 613

Answers (1)

patrickmcgraw
patrickmcgraw

Reputation: 2495

I did some digging on this because I didn't immediately know the answer. I found that #build does setup the association models but only from the parent model down to the children. This means that in your example from above, rails is behaving as designed.

>>team = Team.create
>>team_history = team.team_histories.create
>>player = team_history.players.create
>>player.team_histories.count
1
>>player2 = team_history.players.build
>>player2.team_histories.count
0

This is totally as expected. If you called:

>>team_histories.players

your new player would be in the list. So if instead of:

>>player2.save

you ran:

>>team_histories.save

your new player would be saved.

Jonathan Wallace's answer on this SO question says basically the same thing.

Upvotes: 1

Related Questions