写命名范围的更好方法是什么?

时间:2011-07-04 11:53:51

标签: ruby-on-rails ruby named-scope

此命名范围正常。

named_scope :search, lambda {|search_txt|
      {
        :conditions => ["field1 like ? or field2 like ? or field3 like ?","#{search_txt}%","#{search_txt}%","#{search_txt}%"]
      }
  }

而不是在条件下三次写search_txt。在条件中只传递一次search_txt可以处理相同的情况吗?

这样的东西
named_scope :search, lambda {|search_txt|
      {
        :conditions => ["field1 like ? or field2 like ? or field3 like ?","#{search_txt}%"]
      }

}

2 个答案:

答案 0 :(得分:7)

我不知道这是否适用于范围,但还有另一种写条件的方法:

MyModel.all(:conditions=>['field_1 LIKE :q OR field_2 LIKE :q OR field_3 LIKE :q', {:q=> 'search_txt'}])

答案 1 :(得分:1)

这应该有效:

named_scope :search, lambda {|search_txt|
  {
    :conditions => ["field1 like :q or field2 like :q or field3 like :q",{:q => "#{search_txt}%"}]
  }

}