加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:39:55 所属栏目:百科 来源:网络整理
导读:在rails中,保存active_record对象时,也会保存其关联的对象.但是has_one和has_many关联在保存对象时有不同的顺序. 我有三个简化模型: class Team ActiveRecord::Base has_many :players has_one :coachendclass Player ActiveRecord::Base belongs_to :team
在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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读