Rails查询无法正常工作

时间:2014-02-10 10:03:28

标签: ruby-on-rails

我有一个带过滤器的页面,它不能正常工作,如果设置了所有过滤器,它都有效。 但是如果没有设置类别过滤器而另外两个设置它将无法工作(它显示所有产品)。如果设置了类别并且再次设置了库存价格,则与之前相同,它显示仅按类别过滤的事物。 我的模型是product.rb

def self.categorized(category=nil)
  return self.where("category_id LIKE ?",category ) if category
  self
end
def self.priced(price=nil)
  return self.where("price < 50") if price=="low"
  return self.where("price < 100 and price > 50") if price=="mid"
  return self.where("price > 100") if price=="high"
  self
end

def self.stocked(stock=nil)
  return self.where("stock > 0") if stock=="available"
  return self.where("stock = 0" ) if stock=="out"
  self
end
def self.catalog(params)
 page = params[:page]
 category = params[:category]
 stock = params[:stock]
 price = params[:price]
 self.stocked(stock).priced(price).categorized(category)
  .paginate(:page =>page).limit(9)
end

2 个答案:

答案 0 :(得分:3)

您的问题是self并不完全符合您的预期。由于这些是类级方法self总是引用“普通”类,而不是已经“聚合”您使用的where子句的东西。你想要的是返回一些不会改变你到目前为止的链式查询的东西。

def self.categorized(category=nil)
  return self.where("category_id LIKE ?",category ) if category
  scoped
end

应该有效

(更新了我的回答,不确定Product.none是否按照我的想法行事,而且只适用于Rails 4.0。)

答案 1 :(得分:2)

使用范围,

scope :priced, where("price < 50")
scope :stocked, where("stock > 0")

然后拨打Product.priced.stocked

详细了解范围以及如何将变量传递到范围here

编辑:

这将是您完整的过滤代码..请告诉我这是否有效。

  scope :categorized, (lambda do |category|
    where("category_id LIKE ?",category ) if category   
  end)

  scope :priced, (lambda do |price|
     where("price < 50") if price=="low"
     where("price < 100 and price > 50") if price=="mid"
     where("price > 100") if price=="high"
  end)

  scope :stocked, (lambda do |stock|
     where("stock > 0") if stock=="available"
     where("stock = 0" ) if stock=="out"
  end)

def self.catalog(params)
 page = params[:page]
 category = params[:category]
 stock = params[:stock]
 price = params[:price]
 @products = Product.scoped
 @products.stocked(stock) if stock
 @products.priced(price) if price
 @products.categorized(category) if category
 @products.paginate(:page =>page).limit(9)    
end