【问题标题】:Deprecation warning when using has_many :through :uniq in Rails 4在 Rails 4 中使用 has_many :through :uniq 时的弃用警告
【发布时间】:2013-05-10 07:36:17
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord ruby-on-rails-4


    【解决方案1】:

    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
    

    【讨论】:

    【解决方案2】:

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

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

    也许只有我一个人,但使用范围块来扩展关联代理似乎很不直观。

    【讨论】:

      猜你喜欢
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      相关资源
      最近更新 更多