开发者

How can I find date range in Ruby on Rails?

I want to search data within the given date range. I have a database with having details of name, venue, start_at and end_at. I can search name and venue by defining find method in controller.following is my controller code.

def find
  @events=Event.find(:all, :conditions=>["venue = ? OR name = ?", params[:search_string], params[:search_string]])
end

Then it will find venue or name. But when I add start_at into this code it will return an exception. how can i search relevant date range from the database? plz anybody can help me? I am using postgresql and ruby 1.8.7 and rail开发者_如何转开发s 2.3.8 versions.

I changed my find method as follows...

def find    
  if (params[:search_string])
    @events=Event.find(:all, :conditions=>["venue = ? OR name = ?", params[:search_string], params[:search_string]])
  else 
    @events= Event.all(:conditions => ["start_at >= ? AND end_at <= ?",  params[:start_at], params[:end_at]])
  end
end                                                           

first if statement was properly working. but else part is not working. there is no exception. it will not retrieve date related data from database. I add this if statement into my code due to not retrieving data. can anybody help me to correct this second part? I enter date in my search textbox. but it will not retrieve any data.


Have a look at http://guides.rubyonrails.org/active_record_querying.html Try something like:

@events = Event.where("(venue = ? OR name = ?) AND start_at >= ? AND end_at <= ?", params[:search_string], params[:search_string], params[:start_at], params[:end_at])

Edit

In Rails 2.3.x, it should be

@events = Event.all(:conditions => ["(venue = ? OR name = ?) AND start_at >= ? AND end_at <= ?", params[:search_string], params[:search_string], params[:start_at], params[:end_at]])

Notice that the conditions is given as an array.


I could find a way to search a data within given date range. I did this separately.I created two text_field_tag in my layout and created controller code as follow.

    def find
    @events= Event.all(:conditions => ["start_at >= ? AND end_at <= ?",  params[:search], params[:search_string]])

    end

Then I added following code in layout.

    <span style="text-align: right">
    <% form_tag "/events/find" do %>
    <%= text_field_tag :search%>
    <%= text_field_tag :search_string %>
    <%= submit_tag "search" %>
    <% end %>
    </span>

I got data from database.. Now I want to combine these two. finding a data by date range needs two text_field_tag and finding a data by name only need one text_field _tag. So how can I do this? need your help further more....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜