【问题标题】:Using uniq in a has_and_belongs_to_many relationship in Rails 4在 Rails 4 的 has_and_belongs_to_many 关系中使用 uniq
【发布时间】:2013-12-12 03:41:25
【问题描述】:

我正在尝试对 has_and_belongs_to_many 关系实施唯一约束,如下所示:

class User
  has_and_belongs_to_many :foos, uniq: true
end

因为当我调用user.foos 时我只想要唯一的foos,所以我添加了uniq 选项。自从升级到 Rails 4 后,我开始收到以下警告:

弃用警告:您的以下选项 User.has_and_belongs_to_many :foos 声明已弃用: :uniq。 请改用范围块。例如:

  has_many :spam_comments, conditions: { spam: true }, class_name: 'Comment'

应该改写如下:

  has_many :spam_comments, -> { where spam: true }, class_name: 'Comment'

我尝试了许多不同的组合,并通读了源代码,但不知道如何编写唯一约束以消除警告?

【问题讨论】:

  • 也许this 可以提供帮助

标签: ruby-on-rails activerecord ruby-on-rails-4


【解决方案1】:
class User
  has_and_belongs_to_many :foos, -> { uniq }
end

根据documentation here

【讨论】:

  • 所以,但是如果您使用after_add 回调,它将每次都重复
  • 我知道这是一个旧答案,但无论如何都要发表评论。感谢它运行良好并将DISTINCT 添加到生成的SQL 中。但是您拥有的链接没有显示这方面的信息。
  • 在 Rails 5.1 中这将不再起作用,应该是:has_and_belongs_to_many : foos, -> { distinct }
  • 奇怪的是,这个验证似乎并没有抢占数据库级别的约束。也就是说,如果您还在迁移中设置了add_index :join_table, [:user_id, :foo_id], unique: true,然后您编写了一个测试/规范来查看当您尝试将相同的foo 添加到给定的user 多次时会发生什么,重复的条目不会被数据模型验证捕获,会被传递到数据库并引发错误。如果有人有任何见解,我会很高兴听到它。
  • @RyanLue 我相信这是因为 uniq/distinct 只影响从数据库请求的内容,而不影响保存到其中的模型的行为。 discussion in this q/a
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多