#112 Anonymous Scopes

The scoped method allows you to generate named scopes on the fly. In this episode I show how to use anonymous scopes to improve the conditional logic which was used in the previous episode on advanced search form.
# config/initializers/global_named_scopes.rb
class ActiveRecord::Base
  named_scope :conditions, lambda { |*args| {:conditions => args} }
end

# models/search.rb
def find_products
  scope = Product.scoped({})
  scope = scope.conditions "products.name LIKE ?", "%#{keywords}%" unless keywords.blank?
  scope = scope.conditions "products.price >= ?", minimum_price unless minimum_price.blank?
  scope = scope.conditions "products.price <= ?", maximum_price unless maximum_price.blank?
  scope = scope.conditions "products.category_id = ?", category_id unless category_id.blank?
  scope
end

你可能感兴趣的:(ActiveRecord)