【问题标题】:Conditions deprecated in rails use scope blockrails 中不推荐使用的条件使用范围块
【发布时间】:2025-12-14 02:45:01
【问题描述】:

我收到此警告

DEPRECATION WARNING: The following options in your Product.has_many :recommended_users declaration are deprecated: :conditions. 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 :current_products, :class_name => "Product", :through => :associations, :source => :product, :conditions => ["associations.category = ?", 1]

谁能帮帮我?

【问题讨论】:

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


【解决方案1】:

使用这个

has_many :current_products, -> { where "associations.category = ?", 1}, :class_name => "Product", :through => :associations, :source => :product

-或-

has_many :current_products, -> { where "associations.category = 1"}, :class_name => "Product", :through => :associations, :source => :product

请参阅 API dock 了解语法和其他详细信息

您也可以使用named_scope。参考Named scope better than conditions

【讨论】: