Rails,使用named_scope

时间:2009-07-21 08:48:21

标签: ruby-on-rails

我需要从搜索表单中选择一些动态价格范围。我应该如何处理范围?我正在寻找像这样的东西

Painting.price_range(['1..500','2000..5000'])

SELECT * FROM paintings WHERE price BETWEEN 1..500 **OR** BETWEEN 2000..5000 etc.

祝你好运。 AsbjørnMorell。

2 个答案:

答案 0 :(得分:4)

named_scope :price_range, :conditions => ["(price BETWEEN 1 AND 500) OR (price BETWEEN 2000 AND 5000)"]

OR

named_scope :price_range, :conditions => ["(price ?) OR (price ?)", (1..500).to_s(:db), (2000..5000).to_s(:db)]

动态

named_scope :price_between, lambda { |from, to| { :conditions => ['price > ? AND price <= ?', from, to] } }

named_scope :price_between, lambda { |from, to| { :conditions => ['price BETWEEN ? AND ?', from, to] } }

- &GT;

MyModel.price_between(1,100)

答案 1 :(得分:2)

您需要在named_scope上使用lambda。以下应该有效:

  named_scope :price_range, lambda { |ranges|
    { 
      :conditions => ["(" + 
         ranges.collect {"price between ? and ?"}.join(" or ") + 
                      ")"] +
         ranges.collect {|r| [r.min, r.max]}.flatten 
    }
  }

第一个ranges.collect创建与范围一样多的“between ? and ?”检查,然后第二个ranges.collect将范围展平,并将它们作为要清理的条件添加到条件中。为了安全起见,我把括号括在了ors上。