开发者

Better way to write named scope?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜