在使用:uniq => true和has_many :through时,Rails4引入了一个弃用警告。例如:
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声明的正确方法是什么?
发布于 2013-05-23 05:45:14
需要将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-08-27 13:58:05
除了Dylans answer之外,如果您碰巧扩展了与模块的关联,请确保在作用域块中链接它(而不是单独指定它),如下所示:
has_many :donors,
-> { extending(DonorExtensions).order(:name).uniq },
through: :donations
也许只有我这样认为,但使用作用域块来扩展关联代理似乎非常不直观。
https://stackoverflow.com/questions/16569994
复制相似问题