Rails 中的双向图
我有一个简单的模型“Match”,它应该保存两个对象(同类)之间的双向链接。
class Match < ActiveRecord::Base
belongs_to :obj1, :class_name => "MyModel", :foreign_key => :obj1_id
belongs_to :obj2, :class_name => "MyModel", :foreign_key => :obj2_id
...
end
我遇到的问题是,对于我发现的每个双向匹配,我都会得到两个数据库条目。 例如 1:obj1-> 对象2, 2:obj2-> obj1
如何使用 validates_uniqueness_of 来避免这种情况? 我尝试过
validates_uniqueness_of :obj1_id, :scope => :obj2_id
validates_uniqueness_of :obj2_id, :scope => :obj1_id
,但没有成功。
I have a simple model "Match" that is supposed to save the bi-directional link between two objects (of the same kind).
class Match < ActiveRecord::Base
belongs_to :obj1, :class_name => "MyModel", :foreign_key => :obj1_id
belongs_to :obj2, :class_name => "MyModel", :foreign_key => :obj2_id
...
end
The problem I have is that for each bi-directional Match that I discover I get two database entries. E.g.
1: obj1 -> obj2,
2: obj2 -> obj1
How can I use validates_uniqueness_of
to avoid this here? I tried
validates_uniqueness_of :obj1_id, :scope => :obj2_id
validates_uniqueness_of :obj2_id, :scope => :obj1_id
but that didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很难看。 添加一些唯一的数据库索引。
Pretty ugly. Add some unique database indexes.