When an active_record is saved, is it saved before or after its associated object(s)?
Posted
by SeeBees
on Stack Overflow
See other posts from Stack Overflow
or by SeeBees
Published on 2010-04-20T03:20:14Z
Indexed on
2010/04/20
3:53 UTC
Read the original article
Hit count: 184
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 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 when team.save!
is called, it first calls player.save!
. player
needs to validate the presence of the id
of the associated team
. But at the time player.save!
is called, team
hasn't been saved yet, and therefore, team_id
doesn't yet exist for player
. This fails the player
's validation, so the error occurs.
But on the other hand, team
is saved before coach.save!
, otherwise the first example will get the same error as the second one.
So I've concluded that when a has_many bs, a.save! will save bs prior to a. When a has_one b, a.save! will save a prior to b. If I am right, why is this the case? It doesn't seem logical to me. Why do has_one and has_many association have different order in saving? Any ideas? And is there any way I can change the order? Say I want to have the same saving order for both has_one and has_many. Thanks.
© Stack Overflow or respective owner