Forum: Ruby on Rails How to build search form dynamically

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
B76c7e88660d72aaffcb4b671cebbf3a?d=identicon&s=25 ror.man83 (Guest)
on 2008-10-12 13:30
(Received via mailing list)
Hi all,
I want to search events based on its name, location, start date, end
date and ...
if i am using sql, i can do this
sql= "select * from events where 1=1"
if params[:name]
   sql +=" name = #{params[:name]}
if params[:location]
   sql +=" location = #{params[:location]}

Are there other ways to construct search builder?
ex: events= Events.find_by_object(search_criteria)
search_criteria = {name=>params[:name],....}

Further more, I want to search event by posted, by attending, by most
popular, by latest.
I do it as following "Search events for the name #{params[:name]} and
sort option #{params[:sort_option]}"
      @sort_option = params[:sort_option]
      if "POSTED"==@sort_option
        @events =, :conditions=>['
event_name like ?','%'+params[:name]+'%'])
        # search all events current user will attend]
      elsif "ATTEND"==@sort_option
        @events =,:select=>"events.*",
        :joins=>" join event_attendants on  event_attendants.event_id
= " ,
        :conditions=>[' events.event_name like ? and
event_attendants.attendant_mail =? and
      elsif "POPULAR"==@sort_option
        @events =,:select=>"events.*",
        :joins=>" join event_attendants on  event_attendants.event_id
= " ,
        :conditions=>[' events.event_name like ? and
event_attendants.aasm_state in (?)','%'+params[:name]+'%',
%w{will_attend might_attend no_response}],
count(event_attendants.event_id) desc")
        @events =, :conditions=>['
event_name like ?','%'+params[:name]+'%'],:order=>" created_at

My questions
+ those codes are only dealing with params[:name], if some params
involve ( location,...) they will become messy how  to avoid it?
+ I want to re factor those code but really don't know how to do, or
where to start?
My Domain Objects
Network (1) ---> (n) Event (1) --> (n) EventAttendant (n) --> User

I'm very new to Ruby and RoR.
I'd appreciate your help.
Thanks and regards,
This topic is locked and can not be replied to.