Ruby-on-rails 在 Rails 4 中使用 has_many :through :uniq 时的弃用警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16569994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deprecation warning when using has_many :through :uniq in Rails 4
提问by Ryan Crispin Heneise
Rails 4 has introduced a deprecation warning when using :uniq => true with has_many :through. For example:
当使用 :uniq => true 和 has_many :through 时,Rails 4 引入了弃用警告。例如:
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'
What is the correct way to rewrite the above has_many declaration?
重写上述 has_many 声明的正确方法是什么?
回答by Dylan Markow
The uniqoption 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 => :donationspart):
该uniq选项需要移动到作用域块中。请注意,scope 块需要是第二个参数 to has_many(即您不能将它留在行尾,它需要移动到:through => :donations部件之前):
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"
becomes:
变成:
has_many :donors, -> { where("age < 30").order("name").uniq }, :through => :donations
回答by Andrew Hacking
In addition to Dylans answer, if you happen to be extending the association with a module, make sure that you chain it in the scope block (as opposed to specifying it separately), like so:
除了 Dylans 答案之外,如果您碰巧扩展了与模块的关联,请确保将其链接到作用域块中(而不是单独指定它),如下所示:
has_many :donors,
-> { extending(DonorExtensions).order(:name).uniq },
through: :donations
Maybe its just me but it seems very unintuitive to use a scope block to extend an association proxy.
也许它只是我,但使用范围块来扩展关联代理似乎非常不直观。

