rails中不推荐使用的条件使用范围块

时间:2014-03-28 04:40:16

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

我收到了这个警告

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]

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

使用此

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

-OR -

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

有关语法和其他详细信息,请参阅 API dock

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