开发者

Better way to write named scope?

开发者 https://www.devze.com 2023-03-17 07:21 出处:网络
This named scope is working fine. named_scope :search, lambda {|search_txt| { :conditions => [\"field1 like ? or field2 like ? or field3 like ?\",\"#{search_txt}%\",\"#{search_txt}%\",\"#{search_t

This named scope is working fine.

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

Instead of writing search_txt three time in conditions. Can I handle the same scenario with passing search_txt only once in conditions ?

Something like

nam开发者_如何学Pythoned_scope :search, lambda {|search_txt|
      {
        :conditions => ["field1 like ? or field2 like ? or field3 like ?","#{search_txt}%"]
      }

}


I don't know if this works in a scope, but there is another way to write conditions:

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


This should work:

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

}

0

精彩评论

暂无评论...
验证码 换一张
取 消