Forum: Ruby on Rails How to build search form dynamically

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
ror.man83 (Guest)
on 2008-10-12 15: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
      logger.info "Search events for the name #{params[:name]} and
sort option #{params[:sort_option]}"
      @sort_option = params[:sort_option]
      if "POSTED"==@sort_option
        @events = current_user.events.find(:all, :conditions=>['
event_name like ?','%'+params[:name]+'%'])
        # search all events current user will attend]
      elsif "ATTEND"==@sort_option
        @events = current_user.events.find(:all,:select=>"events.*",
        :joins=>" join event_attendants on  event_attendants.event_id
= events.id " ,
        :conditions=>[' events.event_name like ? and
event_attendants.attendant_mail =? and
event_attendants.aasm_state=?','%'+params[:name]
+'%',current_user.email,"will_attend"])
      elsif "POPULAR"==@sort_option
        @events =
current_network.events.find(:all,:select=>"events.*",
        :joins=>" join event_attendants on  event_attendants.event_id
= events.id " ,
        :conditions=>[' events.event_name like ? and
event_attendants.aasm_state in (?)','%'+params[:name]+'%',
%w{will_attend might_attend no_response}],
        :group=>"event_attendants.event_id",:order=>"
count(event_attendants.event_id) desc")
      else
        @events = current_network.events.find(:all, :conditions=>['
event_name like ?','%'+params[:name]+'%'],:order=>" created_at
desc")
      end

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,
Van
This topic is locked and can not be replied to.