在Rails 4中的has_and_belongs_to_many关系中使用uniq

Gav*_*ler 3 activerecord ruby-on-rails ruby-on-rails-4

我正试图在这样的has_and_belongs_to_many关系上实现一个独特的约束:

class User
  has_and_belongs_to_many :foos, uniq: true
end
Run Code Online (Sandbox Code Playgroud)

因为我foos打电话时只想要独一无二user.foos,所以我添加了uniq选项.自升级到Rails 4以来,我开始收到以下警告:

弃用警告:不推荐使用User.has_and_belongs_to_many:foos声明中的以下选项:: uniq.请改用示波器块.例如,以下内容:

  has_many :spam_comments, conditions: { spam: true }, class_name: 'Comment'
Run Code Online (Sandbox Code Playgroud)

应该改写如下:

  has_many :spam_comments, -> { where spam: true }, class_name: 'Comment'
Run Code Online (Sandbox Code Playgroud)

我已经尝试了许多不同的组合,并通读源,但无法弄清楚如何编写唯一约束来删除警告?

ush*_*sha 18

class User
  has_and_belongs_to_many :foos, -> { uniq }
end
Run Code Online (Sandbox Code Playgroud)

根据这里文件

  • 并且在rails 5.1中这将不再起作用,应该是:`has_and_belongs_to_many:foos, - > {distinct}` (3认同)