ruby-on-rails – 保存活动记录,保存关联对象的顺序?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 保存活动记录,保存关联对象的顺序?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在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!返回true.

但在另一个测试中:

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_associated”来实现这一目标

检查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

在你的控制器中

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相关文章