在轨道4 uniq的:通过:使用的has_many时,德precation警告轨道、uniq、precation、has_many

2023-09-09 21:58:50 作者:Only one for you

轨道4已经在使用引进了德precation警告:uniq的=>真正具有的has_many:通过。例如:

Rails 4 has introduced a deprecation warning when using :uniq => true with has_many :through. For example:

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

产生以下警告:

Yields the following warning:

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声明的正确方法?

What is the correct way to rewrite the above has_many declaration?

推荐答案

uniq的选项需要移动到一个范围块。需要注意的是范围块需要是第二个参数的has_many (即你不能在该行的末尾离开它,它需要在:通过=>:捐款部分):

The uniq option needs to be moved into a scope block. Note that the scope block needs to be the second parameter to has_many (i.e. you can't leave it at the end of the line, it needs to be moved before the :through => :donations part):

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

这可能看起来很奇怪,但它使一些更有意义,如果你考虑在你有多个参数的情况。例如,这

It may look odd, but it makes a little more sense if you consider the case where you have multiple parameters. For example, this:

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

变成了:

has_many :donors, -> { where("age < 30").order("name").uniq }, :through => :donations