Tuesday, March 30, 2010

Simple search Ruby on Rails

:::----------------------------------------------------------------------------------:::
Problem

--------->>>
I need to do search function based on date range selected by user.. In my databaase,for my date column i have this format '01-February-2010' but for my calendar format i have this format '01-02-2010'. So i can't get the whole result if i don't convert my date selected from calendar into my date format in my database. Basically, i need to convert this format "01-02-2010" into this format "01-February-2010".
My senior recommended me to use Date::MONTHNAMES to convert them.Thanks to him for helping me out.. Senpai,thanks a lot..(^_-)


:::----------------------------------------------------------------------------------:::
Coding3.....

----------->> controller
def date

from = params[:from_date].split("-")
start_date = from[0] + '-' + Date::MONTHNAMES[from[1].to_i] + '-'+ from[2]

to = params[:end_date].split("-")
to_date = to[0] + '-' + Date::MONTHNAMES[to[1].to_i] + '-' + to[2]

@date_search = Hacked.date_search(start_date,to_date)

end

>>>>>>> line 1 & 3 = get parameter value from view/search.rhtml and then split them into 3 part using .split and have this symbol("-") in between.
line 2 & 4 = combine them together again but for the [1], have them in full monthname using Date::MONTHNAMES eg. 'February' & convert them to integer.
line 5 =

----------> view/search.rhtml
<% form tag({:controller => :urcontrollername, :action => uractionname }, :method => 'get' ) do %>
Start Date
<% calendar_select_tag :from_date %>
End Date
<% calendar_select_tag :to_date %>
<% search_tag "Search!"


>>>>>> this form will accept 2 parameters value from users using calendar_select_tag and then refer to controller..

----------> view/result.rhtml
put ur own coding here, to view ur result...:)

>>>>>> results of the search should be displaying here


----------> urmodelname.rb

def self.date_search(start_date,to_date)

@date_search = Hacked.find(:all, :conditions => ["date between ? and ?",start_date,to_date]
end


>>>>>>> this will process ur request by finding all related data within the conditions

2 comments: