在raails 4中使用has_many:through:uniq时的弃用警告

Boo*_*age 95 activerecord ruby-on-rails ruby-on-rails-4 rails-activerecord

使用时,Rails 4引入了弃用警告:uniq => true with has_many:through.例如:

has_many :donors, :through => :donations, :uniq => true
Run Code Online (Sandbox Code Playgroud)

产生以下警告:

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'
Run Code Online (Sandbox Code Playgroud)

重写上述has_many声明的正确方法是什么?

Dyl*_*kow 236

uniq选项需要移动到范围块中.请注意,范围块需要是第二个参数has_many(即,您不能将它留在行的末尾,它需要在:through => :donations部件之前移动):

has_many :donors, -> { uniq }, :through => :donations
Run Code Online (Sandbox Code Playgroud)

它可能看起来很奇怪,但如果考虑有多个参数的情况,它会更有意义.例如,这个:

has_many :donors, :through => :donations, :uniq => true, :order => "name", :conditions => "age < 30"
Run Code Online (Sandbox Code Playgroud)

变为:

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

  • 我实际上在升级到Rails 4的书中看到了它(它正在进行中):http://www.upgradingtorails4.com/ - 未能在其他任何地方找到它. (6认同)

And*_*ing 5

除了Dylans的回答,如果您正在扩展与模块的关联,请确保将其链接到范围块(而不是单独指定),如下所示:

has_many :donors,
  -> { extending(DonorExtensions).order(:name).uniq },
  through: :donations
Run Code Online (Sandbox Code Playgroud)

也许只是我,但使用范围块来扩展关联代理似乎非常不直观.