Rails:从下拉列表中搜索数年和数月

时间:2018-01-17 12:27:22

标签: ruby-on-rails

我使用Rails 5.1,我试图使用两个下拉选择列表-1进行搜索。年,2个月 - 以及提交按钮。

在我看来:

<%= form_tag jobs_path, method: :get do %>
<%= select_year(Date.today, {:prompt => "Year",:start_year => DateTime.now.year,:end_year => DateTime.now.year - 7, prefix: 'select'},{:field_name => 'year', :id => 'start-year'}) %>
  <%= select_month(Date.today, {:prompt => "month",use_short_month: true, prefix: 'select'},{:field_name => 'month', :id => 'start-month'}) %>
  <%= submit_tag("Search Job", :id=>"button", :class=>"Test", :name=>"submit") %>
<%end%>

在我的jobs_controller.rb中:

  # GET /jobs.json
  def index
    if params[:year].present? or params[:month].present?
       month_with_leading_zero = params[:month].to_s.rjust(2, "0")
       start_date = "#{params[:year]}-#{month_with_leading_zero}-1"
       end_date = Time.now.strftime("%Y-%m-%d")
       @jobs = Job.where("datum_auftrag BETWEEN ? AND ?", start_date, end_date)
    else
      @search = Job.ransack(params[:q])
      @jobs = @search.result
    end
  end

在我的数据库中,日期以格式保存:yyyy-mm-dd eg。 2011-01-20

点击提交按钮会忽略过滤,而是打印所有作业:

  

开始GET   “/ UTF8工作=%E2%9C%93&放大器;起始日期%5Byear%5D = 2016&放大器;起始日期%5Bmonth%5D = 1&安培;提交=搜索+招聘”   for :: 1 at 2018-01-17 14:01:54 +0100 Processing by   JobsController #index为HTML参数:{“utf8”=&gt;“✓”,   “start_date”=&gt; {“年”=&gt;“2016”,“月”=&gt;“1”},“提交”=&gt;“搜索工作”}   在布局/应用程序中渲染jobs / index.html.erb已渲染   jobs / _job_links.html.erb(38.5ms)作业加载(5.5ms)SELECT jobs。*   FROM jobs(1.3ms)SELECT COUNT()FROM manuscripts WHERE   manuscriptsjob_id = 20(2.2ms)SELECT COUNT()FROM   manuscripts WHERE manuscriptsjob_id = 21

我错过了什么?

1 个答案:

答案 0 :(得分:1)

1在索引页面上创建搜索表单

<%= form_tag your_index_action_path, method: :get do%>
  <%= select_year(Date.today, {:prompt => "Year",:start_year => DateTime.now.year,:end_year => DateTime.now.year - 7, prefix: 'select'},{:field_name => 'year', :id => 'start-year'}) %>
  <%= select_month(Date.today, {:prompt => "month",use_short_month: true, prefix: 'select'},{:field_name => 'month', :id => 'start-month'}) %>
  <%= submit_tag("Search Job", :id=>"button", :class=>"Test", :name=>"submit") %>
<%end%>

注意: - 通过索引操作的路径替换your_index_action_path您可以通过运行rake routes

来获取控制台上的路径

2-在您的索引操作中,在控制器端单击提交按钮,您将获得以下参数

{"utf8"=>"✓", "select"=>{"year"=>"2018", "month"=>"1"}, "submit"=>"Search Job", "controller"=>"jobs", "action"=>"index"} permitted: false>

因此,您只需要params[:select][:year]params[:select][:month]

def index
  if params[:select][:year].present? || params[:select][:month].present?
    start_date = (params[:select][:year]+"-" +params[:select][:month]+"-"+Date.today.day.to_s).to_datetime.beginning_of_day
    end_date = Date.today.end_of_day
    @jobs = Job.where("datum_auftrag BETWEEN ? AND ?",start_date, end_date)
  else
    @jobs = Job.all
  end
end

注意: - 它需要根据所选值制作自定义日期,并且我使用了beginning_of_dayend_of_day方法来获得更清晰的搜索结果。

早些时候我给了你一个示例代码,你应该修改它,在这里我再次给你解决方案,请不要只是复制和粘贴使用调试器和pry在控制器端获得选定的日期和年份,但是我实际上已经完成了这个答案。