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)
除了Dylans的回答,如果您正在扩展与模块的关联,请确保将其链接到范围块(而不是单独指定),如下所示:
has_many :donors,
-> { extending(DonorExtensions).order(:name).uniq },
through: :donations
Run Code Online (Sandbox Code Playgroud)
也许只是我,但使用范围块来扩展关联代理似乎非常不直观.
| 归档时间: |
|
| 查看次数: |
22492 次 |
| 最近记录: |