按日期搜索时出现奇怪的错误

时间:2012-08-06 10:23:54

标签: ruby-on-rails search jquery-ui-datepicker

我正在尝试创建报告页面,用户将选择开始和结束日期并推送buttopn报告。然后隐藏的div变得可见。

我的搜索不是部分。

我正在使用jquery_datepicker所以这是我的代码来自视图:

<%= form_tag(:controller => "financial_reports", :action => "index", :method => "post")%>
  <%= datepicker_input "financial_report","start_date", :dateFormat => "dd/mm/yy" %>
  <%= datepicker_input "financial_report","end_date", :dateFormat => "dd/mm/yy" %>
 <%=  submit_tag "Run Report"%>
<% end %>

这是我来自控制器的代码:

  def search
   @financial_reports = current_user.financial_reports.search(params[:start_date], params[:end_date]
  render :index
  end

在我的模型中:

def self.search(from,to)
  find(:all, :conditions => [ "BETWEEN ? AND ?", from, to])
 end

它给了我错误:

    ActiveRecord::StatementInvalid in FinancialReportsController#search 
    SELECT `financial_reports`.* FROM `financial_reports`  WHERE `financial_reports`.`user_id` = 67 AND (BETWEEN NULL AND NULL)

以下:

     Parameters:

  {"utf8"=>"✓",
 "authenticity_token"=>"AMobLLRV3aAlNn6b4Au+1nRP2AN1TLQcBCytBXhDA/g=",
  "type"=>"",
   "financial_report"=>{"start_date"=>"05/08/2012",
      "end_date"=>"11/08/2012"},
    "commit"=>"Run Report",
   "method"=>"post"}

我的错误在哪里?

1 个答案:

答案 0 :(得分:1)

如果两个参数始终都设置,您可以使用:

@financial_reports = current_user.financial_reports.where(:created_at => ((params[:start_date].to_date)..(params[:end_date].to_date))

如果不是这样,你可以(例如)这样做:

@financial_reports = current_user.financial_reports

if params[:start_date].present?
  @financial_reports = current_user.financial_reports.where("created_at >= ?", params[:start_date])
end

if params[:end_date].present?
  @financial_reports = current_user.financial_reports.where("created_at <= ?", params[:end_date])
end

您可能希望将其封装在范围中。