96

当使用 :uniq => true 和 has_many :through 时,Rails 4 引入了弃用警告。例如:

has_many :donors, :through => :donations, :uniq => true

产生以下警告:

DEPRECATION WARNING: The following options in your Goal.has_many :donors 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'

重写上述 has_many 声明的正确方法是什么?

4

2 回答 2

239

uniq选项需要移动到范围块中。请注意,范围块需要成为第二个参数has_many(即不能将其留在行尾,需要将其移到:through => :donations部分之前):

has_many :donors, -> { uniq }, :through => :donations

它可能看起来很奇怪,但如果考虑到有多个参数的情况,它会更有意义。例如,这个:

has_many :donors, :through => :donations, :uniq => true, :order => "name", :conditions => "age < 30"

变成:

has_many :donors, -> { where("age < 30").order("name").uniq }, :through => :donations
于 2013-05-22T21:45:13.687 回答
5

除了 Dylans 的回答之外,如果您碰巧要扩展与模块的关联,请确保将其链接在范围块中(而不是单独指定它),如下所示:

has_many :donors,
  -> { extending(DonorExtensions).order(:name).uniq },
  through: :donations

也许它只是我,但使用范围块来扩展关联代理似乎非常不直观。

于 2013-08-27T05:58:05.130 回答