On saving an new active record, in what order are the associated objects saved?
Posted
by Bryan
on Stack Overflow
See other posts from Stack Overflow
or by Bryan
Published on 2010-04-20T03:20:14Z
Indexed on
2010/04/21
1:53 UTC
Read the original article
Hit count: 301
ruby-on-rails
|activerecord
In rails, when saving an active_record object, its associated objects will be saved as well. But has_one and has_many association have different order in saving objects.
I have three simplified models:
class Team < ActiveRecord::Base
has_many :players
has_one :coach
end
class Player < ActiveRecord::Base
belongs_to :team
validates_presence_of :team_id
end
class Coach < ActiveRecord::Base
belongs_to :team
validates_presence_of :team_id
end
I expected that when team.save
is called, team should be saved before its associated coach and players.
I use the following code to test these models:
t = Team.new
team.coach = Coach.new
team.save!
team.save!
returns true.
But in another test:
t = Team.new
team.players << Player.new
team.save!
team.save!
gives the following error:
> ActiveRecord::RecordInvalid:
> Validation failed: Players is invalid
I figured out that team.save!
saves objects in the following order: 1) players, 2) team, and 3) coach. This is why I got the error: When a player is saved, team doesn't yet have a id, so validates_presence_of :team_id
fails in player.
Can someone explain to me why objects are saved in this order? This seems not logical to me.
© Stack Overflow or respective owner