在 rails 中,当保存一个 active_record 对象时,它的关联对象也会被保存。但是 has_one 和 has_many 关联在保存对象时有不同的顺序。
我有三个简化模型:
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
我预计当
team.save
被称为,球队应该在其相关的教练和球员之前被拯救。我使用以下代码来测试这些模型:
t = Team.new
team.coach = Coach.new
team.save!
team.save!
返回真。但在另一个测试中:
t = Team.new
team.players << Player.new
team.save!
team.save!
给出以下错误:> ActiveRecord::RecordInvalid:
> Validation failed: Players is invalid
我发现
team.save!
按以下顺序保存对象:1) 球员、2) 团队和 3) 教练。这就是我收到错误的原因:当玩家被保存时,团队还没有 ID,所以 validates_presence_of :team_id
播放器失败。有人可以向我解释为什么按此顺序保存对象吗?这对我来说似乎不合逻辑。
最佳答案
您应该使用“validates_related”来完成
检查 Here
就像没有检查一样
class Team < ActiveRecord::Base
has_many :players
has_one :coach
validates_associated :players, :coach ###MOST IMPORTANT LINE
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
在您的 Controller 中
t = Team.new
@coach = t.build_coach(:column1=> "value1", :column2=> "value2" ) # This create new object with @coach.team_id= t.id
@players = t.players.build
t.save#This will be true it passes the validation for all i.e. Team, COach & Player also save all at once otherwise none of them will get saved.
关于ruby-on-rails - 保存事件记录,关联对象以什么顺序保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2672317/