Logic for a search method


#1

I’m trying to ask users for a name and a place and then give them a list
of all the names OR all the places OR the names in that place, if you
get me? This is my flawed attempt, I’m passing params correctly so it’s
just the logic within the method I need to sort out, anyone mind
re-factoring it ?

Here’s my code (wrong)

class School < ActiveRecord::Base

has_many :reviews

def self.search(search_by_name,search_by_place)

search_by_name
  find(:all, :conditions => ['name LIKE ?', "%#{search_by_name}%"],

:limit => 100)
end

search_by_place
  find(:all, :conditions => ['place LIKE ?',

“%#{search_by_place}%”], :limit => 100)
end

end

end


#2

A couple of things:

  1. You want to make sure you protect against SLQ injection, so do not
    pass the variables without escaping them. Rails does this for you when
    it substitutes the ? in the find method.

  2. You can use the code below to do what you want.

Hope that helps,

Alberto.

def self.search(params={})
conditions = []
condition_values = []
unless params[:name].blank?
conditions << “name like ?”
condition_values << “%#{params[:name]}%”
end
unless params[:place].blank?
conditions << “place like ?”
condition_values << “%#{params[:place]}%”
end
unless conditions.blank?
self.find(:all, :conditions => [conditions.join(" AND "),
*condition_values], :limit => 100)
else
[]
end
end


#3

On Feb 7, 3:09 pm, bingo bob removed_email_address@domain.invalid wrote:

has_many :reviews
“%#{search_by_place}%”], :limit => 100)
end

end

end

Posted viahttp://www.ruby-forum.com/.

You should take small steps, especially when you are still trying to
get to grips with the language.

I’ll help you a little by pointing out that this can be a single
query. What you are trying to do is find stuff that match the
conditions ‘name LIKE ? OR place LIKE ?’. So this should be a one line
method.

I would also suggest you look up named_scope (railscasts.com has a
screencast about it) which you could use here.

Good luck.


#4

the params in the Controller is a method that returns the hash coming
to the request. So you can pass the whole params method in the call.

@schools = School.search(params)


#5

Alberto (or anyone)…

How do I pass in the params from the controller to use the method…

Something like

@schools = School.search(params[:search_by_name],

params[:search_by_place])

But that gives me …

wrong number of arguments (2 for 1)


#6

alberto wrote:

the params in the Controller is a method that returns the hash coming
to the request. So you can pass the whole params method in the call.

@schools = School.search(params)

Many thanks, after staring at this for while I figured it.

Thanks for your help with this it works great and the idea behind it has
helped me a great deal.

Seems like this is something that I’ll need to do a lot (pass the whole
params hash to some method (where it can be dealt with and return
“stuff”).