【问题标题】:Right way to force uniqueness on a join model? (has_many :through)在连接模型上强制唯一性的正确方法? (has_many:通过)
【发布时间】:2011-04-29 05:54:07
【问题描述】:

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

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

现在,可以在我们的“添加孩子”表单中(仅使用普通嵌套属性)为父母多次添加同一个用户作为孩子。我不确定在ParentsChild 关系中强制唯一性的“正确”方法是什么,尽管我倾向于在数据库层的(parent_id, child_id) 上使用唯一索引(当然使用迁移)。

我确信我也可以在 UsersController::update 方法中强制执行唯一性约束,但希望避免更改该代码(现在它根本不引用父/子,这要归功于表单中的嵌套属性/型号)如果可能的话。我最关心的是确保我们使用“正确”的解决方案。这样做的“正确”或“轨道”方式是什么?

【问题讨论】:

    标签: ruby-on-rails activerecord unique has-many-through


    【解决方案1】:

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

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

    【讨论】:

    • 绝对应该首先查看最简单的解决方案。谢谢!
    • 是的!我花了这么长时间摆弄这个,你的答案正是我需要的。
    • 或在 Rails 4 中,has_many :parents, -&gt; { uniq }, :through =&gt; :children_parents
    • 值得注意的是,这不会停止在连接表中创建重复记录,但它确实返回了 uniq 记录
    • 另外,我得到DEPRECATION WARNING: uniq is deprecated and will be removed from Rails 5.1 (use distinct instead)
    猜你喜欢
    • 2013-06-01
    • 2010-11-20
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2010-09-29
    相关资源
    最近更新 更多