krunal shah
krunal shah

Reputation: 16339

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

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

}

Upvotes: 1

Views: 80

Answers (2)

leenasn
leenasn

Reputation: 1486

This should work:

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

}

Upvotes: 1

Wukerplank
Wukerplank

Reputation: 4176

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'}])

Upvotes: 7

Related Questions