Rails ActiveRecord: Multiple conditions in find Rails ActiveRecord: Multiple conditions in find ruby ruby

Rails ActiveRecord: Multiple conditions in find


Rails 2

find(:all, :conditions => ['name LIKE ?', "%#{search}%"], ['active', 1]) isn't the proper syntax for passing hashes to a method. You can leave the curly braces off of a hash if it is the last argument to a method, but in this case you are passing an array as the last argument.

Use the following instead:

find(:all, :conditions => ["name LIKE ? AND active = ?", "%#{search}%", 1])

or

params = {:search => "%#{search}%", :active => 1}find(:all, :conditions => ["name LIKE :search AND active = :active", params])

Rails 3 and 4

You would probably want to do something more like the following for recent Rails versions:

 scope :active, -> { where(active: true) } scope :name_like, ->(search) { where("name LIKE ?", "%#{search}%") }

And then you'd call it like this:

YourModel.active.name_like("Bunnies")

That allows you to reuse those specific queries in different combinations throughout the application. It also makes the code retrieving the data super easy to read.

If you don't like the scope syntax, you can also define these as class methods:

def self.active  where(active: true)enddef self.name_like(search)  where("name LIKE ?", "%#{search}%")end

You can also chain scopes on the fly. That will allow you to start building a chain of relation objects and then choose to include others based on conditions. Here's what it could look like when applied to the original question to achieve the same results:

results = activeresults = results.name_like(search) if search.present?


Instead of using if-else which would involve a redundancy for checking on active = 1, a simpler syntax would be something like this:

result = where(:active => 1)result = result.where('name like ?', "%#{search}%") unless search.blank?

As far as the error your seeing, it wouldn't appear to be caused by the code that you are posting. A stack trace may help narrow it down further...


i think you are using rails 2

try this.

find(:all, :conditions => ['name LIKE ? and active = 1', "%#{search}%"])

rails 3 syntax

where('name LIKE ? and active = 1', "%#{search}%")