# How to build search form dynamically

**URL:** <https://www.ruby-forum.com/t/how-to-build-search-form-dynamically/150743>\
**Category:** Rails\
**Created:** [October 12, 2008, 1:30pm UTC](https://www.ruby-forum.com/t/how-to-build-search-form-dynamically/150743 "2008-10-12T13:30:53Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ror.man83](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/96bed5/32.png) [@ror.man83](https://www.ruby-forum.com/u/ror.man83)\
**Post date:** [October 12, 2008, 1:30pm UTC](https://www.ruby-forum.com/t/how-to-build-search-form-dynamically/150743/1 "2008-10-12T13:30:53Z")

</div>

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
