首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Rails 4中使用has_many :through :uniq时出现弃用警告

在Rails 4中使用has_many :through :uniq时出现弃用警告
EN

Stack Overflow用户
提问于 2013-05-16 00:08:33
回答 2查看 23K关注 0票数 96

在使用:uniq => true和has_many :through时,Rails4引入了一个弃用警告。例如:

代码语言:javascript
复制
has_many :donors, :through => :donations, :uniq => true

生成以下警告:

代码语言:javascript
复制
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声明的正确方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-23 05:45:14

需要将uniq选项移到作用域块中。请注意,作用域块需要是has_many的第二个参数(即您不能将其留在行尾,它需要移到:through => :donations部分之前):

代码语言:javascript
复制
has_many :donors, -> { uniq }, :through => :donations

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

代码语言:javascript
复制
has_many :donors, :through => :donations, :uniq => true, :order => "name", :conditions => "age < 30"

变成:

代码语言:javascript
复制
has_many :donors, -> { where("age < 30").order("name").uniq }, :through => :donations
票数 239
EN

Stack Overflow用户

发布于 2013-08-27 13:58:05

除了Dylans answer之外,如果您碰巧扩展了与模块的关联,请确保在作用域块中链接它(而不是单独指定它),如下所示:

代码语言:javascript
复制
has_many :donors,
  -> { extending(DonorExtensions).order(:name).uniq },
  through: :donations

也许只有我这样认为,但使用作用域块来扩展关联代理似乎非常不直观。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16569994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档