Using uniq in a has_and_belongs_to_many relationship in Rails 4

早过忘川 提交于 2020-01-23 11:03:26

问题


I'm trying to implement a unique constraint on a has_and_belongs_to_many relationship like so:

class User
  has_and_belongs_to_many :foos, uniq: true
end

Because I only want unique foos when I call user.foos, I added the uniq option. Since upgrading to Rails 4 I've started to get the following warning:

DEPRECATION WARNING: The following options in your User.has_and_belongs_to_many :foos declaration are deprecated: :uniq. Please use a scope block instead. For example, the following:

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

should be rewritten as the following:

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

I've tried a number of different combinations, and read through the source, but can't figure out how to write the unique constraint to remove the warning?


回答1:


class User
  has_and_belongs_to_many :foos, -> { uniq }
end

According to the documentation here



来源:https://stackoverflow.com/questions/20226525/using-uniq-in-a-has-and-belongs-to-many-relationship-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!