强制连接模型唯一性的正确方法? (has_many:通过)
我通过我们的用户表建立了父/子关系,模型如下:
class User < ActiveRecord::Base
# Parents relationship
has_many :children_parents, :class_name => "ParentsChild", :foreign_key => "child_id", :dependent => :destroy
has_many :parents, :through => :children_parents
# Children relatiopnship
has_many :parents_children, :class_name => "ParentsChild", :foreign_key => "parent_id", :dependent => :destroy
has_many :children, :through => :parents_children
...
end
在parents_child.rb中:
class ParentsChild < ActiveRecord::Base
belongs_to :parent, :class_name => "User"
belongs_to :child, :class_name => "User"
end
现在,可以在我们的“添加子项”表单(仅使用普通嵌套属性)中添加相同的用户作为孩子多次为父母。我不确定强制 ParentChild 关系唯一性的“正确”方法是什么,尽管我倾向于在数据库层的 (parent_id, child_id)
上建立唯一索引(使用迁移课程)。
我确信我也可以在 UsersController::update 方法中强制执行唯一性约束,但更愿意避免更改该代码(现在它根本不引用父母/孩子,这要归功于表单/模型中的嵌套属性)如果可能的。我最关心的是确保我们使用“正确的”解决方案。执行此操作的“正确”或“导轨”方法是什么?
I have a parent/child relationship via our users table, with models as such:
class User < ActiveRecord::Base
# Parents relationship
has_many :children_parents, :class_name => "ParentsChild", :foreign_key => "child_id", :dependent => :destroy
has_many :parents, :through => :children_parents
# Children relatiopnship
has_many :parents_children, :class_name => "ParentsChild", :foreign_key => "parent_id", :dependent => :destroy
has_many :children, :through => :parents_children
...
end
And in parents_child.rb:
class ParentsChild < ActiveRecord::Base
belongs_to :parent, :class_name => "User"
belongs_to :child, :class_name => "User"
end
Right now, it is possible in our "add children" form (just using vanilla nested attributes) to add the same user as a child multiple times for parents. I am not sure what the 'right' way to go about forcing uniqueness in the ParentsChild relationship, although I am leaning towards a unique index on (parent_id, child_id)
at the database layer (using a migration of course).
I am sure I could also enforce uniqueness constraints in the UsersController::update method, but would prefer to avoid changing that code (right now it doesn't reference parents/children at all, thanks to nested attributes in the form/model) if possible. I am most concerned with making sure we use the "proper" solution. What is the 'right' or 'rails' way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 has_many :through ,您可以指定 :uniq 作为选项,如下所示:
Using has_many :through, you can specify :uniq as an option, like this: