has_many 关联与 has_many 中的 own_to 引用发生混乱
我的数据类似于这样:
class Team < ActiveRecord::Base
has_many :persons
belongs_to :leader, :class_name => "Person"
end
class Person < ActiveRecord::Base
belongs_to :team
end
我像这样创建团队:
@team = Team.new
for (each new person as p)
new_person = @team.persons.build
new_person.name = p.name
if p.is_marked_as_leader
@team.leader = new_person
end
end
@team.save
当我列出@team.persons时,@team.leader具有第一个id,我猜是因为@team.save在人员之前保存了领导者关联。我需要它们按照提供的顺序排列,其中 :leader own_to 引用我的 has_many :persons 中的 ID 之一,
谢谢!
My data resembles this:
class Team < ActiveRecord::Base
has_many :persons
belongs_to :leader, :class_name => "Person"
end
class Person < ActiveRecord::Base
belongs_to :team
end
I create the Team like this:
@team = Team.new
for (each new person as p)
new_person = @team.persons.build
new_person.name = p.name
if p.is_marked_as_leader
@team.leader = new_person
end
end
@team.save
When I list @team.persons, @team.leader has the first id, I guess because @team.save is saving the leader association before persons. I need them to be in the order they are provided, where the :leader belongs_to references one of the ID's within my has_many :persons
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应该依赖 ID 的任何特定顺序,可能会发生很多事情。您可以分配另一个数据库列来以某种方式表示顺序。
如果您想这样做,只需在创建人员时保存人员,因为那时将分配 ID:
如果您担心数据库一致性,请包装
for
循环和 < code>@team.save 在事务中,因此如果其中一个失败,它们都会回滚。You shouldn't rely on ID's to be in any particular order, there are a lot of things that can happen. You could assign another DB column to represent the ordering somehow.
If you want to do it though, just save the people as you create them, since that is when the ID's will get assigned:
If you're worried about database consistency, wrap the
for
loop and the@team.save
in a transaction, so they all get rolled back if one fails.