gpt4 book ai didi

ruby-on-rails - 使用 has_many 时弃用警告 :through :uniq in Rails 4

转载 作者:行者123 更新时间:2023-12-03 04:54:50 24 4
gpt4 key购买 nike

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

最佳答案

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

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

关于ruby-on-rails - 使用 has_many 时弃用警告 :through :uniq in Rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16569994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com