铁路模型:将 validates_uniqueness_of 与关联实体的属性范围一起使用?
我的模型定义如下,
class One <Active:Record:Base
{
has_and_belongs_to_many :twos, {:join_table => 'map__ones__twos'}
}
class Two <Active:Record:Base
{
has_and_belongs_to_many :ones, {:join_table => 'map__ones__twos'}
}
我希望两个的名称属性对于一个的范围应该是唯一的。这意味着属于一个人的所有两人都应该有唯一的名字。在这里,我无法在两个模型中指定如下所示的内容,
validates_uniqueness_of :name, :scope => one_id
因为 on_id 不是二元表的列。相反,one_id 和two_id 通过表map_ones_twos 相互映射(多对多关系)
请建议
I have Model defined as below
class One <Active:Record:Base
{
has_and_belongs_to_many :twos, {:join_table => 'map__ones__twos'}
}
class Two <Active:Record:Base
{
has_and_belongs_to_many :ones, {:join_table => 'map__ones__twos'}
}
I want that name attribute of two should be unique for scope of one. That means all of twos belonging to one should have unique name. Here i can not specify some thing like below in Two model
validates_uniqueness_of :name, :scope => one_id
because on_id is not a column of twos table. Rather one_id and two_id are mapped to each other through table map_ones_twos (many to many relationship)
Please suggest
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我经常发现使用 has_and_belongs_to_many 麻烦多于其价值。当我有多对多关系时,我创建一个连接表并为其创建一个模型。然后,连接模型可以验证两个 id 的唯一性。
请原谅这些名字。我正在使用您问题中的示例表名称。在你的情况下,这看起来像:
你的一个模型看起来像这样:
你的两个模型看起来像这样:
I have often found that using has_and_belongs_to_many is more trouble than it's worth. When I have many-to-many relationships, I create a join table and make a model for it. Then, the join model can have a validation on the uniqueness of the two ids.
Excuse the names. I am using the example table names from your question. In your case, this would look like:
Your One model looks like this:
And your Two model looks like this: