强制连接模型唯一性的正确方法? (has_many:通过)

发布于 2024-09-28 18:50:59 字数 1004 浏览 2 评论 0原文

我通过我们的用户表建立了父/子关系,模型如下:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拒绝两难 2024-10-05 18:50:59

使用 has_many :through ,您可以指定 :uniq 作为选项,如下所示:

  has_many :parents, :through => :children_parents, :uniq => true

Using has_many :through, you can specify :uniq as an option, like this:

  has_many :parents, :through => :children_parents, :uniq => true
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文