Rails 多个搜索参数和默认值

Rails multiple search parameters and defaults

我有一个搜索表单,用于搜索包含 3 个字段的事件模型:incidenttypedayofweekcreated_at。在我的 incidents.index 方法中,我检查搜索参数是否存在。然后根据 created_at 范围等过滤结果。我将如何设置它,以便如果 dayofweekincidenttype 参数为空或空白,它不会在查询中使用它们筛选?本质上,如果选择了 none,则不要使用这些参数,仅使用 created_at.

事件控制器的索引方法:

def index
  if params[:search] && params[:search][:created_at].present?
    start_date, end_date = params[:search][:created_at].split(' - ')
    @incidents = Incident.where(created_at: start_date..end_date).where(dayofweek: params[:search][:dayofweek]).where(incidenttype: params[:search][:incidenttype])
    @dayofweek = params[:search][:dayofweek]
    @incidenttypes = Incident.order("incidenttype").distinct.pluck(:incidenttype)
  else
    @incidents = Incident.all
    @incidenttypes = Incident.order("incidenttype").distinct.pluck(:incidenttype)
  end
end

形式:

<%= form_for(:search, url: incidents_path, method: :get) do |f| %>
  <div class="ui-bordered px-4 pt-4 mb-4">
    <div class="form-row">
      <div class="col-md mb-4">
        <label class="form-label">Type</label>
        <%= f.select :dayofweek, Incident.dayofweeks.keys, {:include_blank=> 'Any days', :selected => @dayofweek}, class: 'custom-select' %>
      </div>
      <div class="col-md mb-4">
        <label class="form-label">Incident Type</label>
        <%= f.select :incidenttype, options_for_select(@incidenttypes, :selected => params[:search][:incidenttype]), {include_blank: true}, class: 'form-control' %>
      </div>
      <div class="col-md mb-4">
        <label class="form-label">Created date</label>
        <%= f.text_field :created_at, class: 'form-control', id: 'tickets-list-created', :autocomplete => :off, value: created_at_from_parameters %>
      </div>
      <div class="col-md col-xl-2 mb-4">
        <label class="form-label d-none d-md-block">&nbsp;</label>
        <button type="submit" class="btn btn-secondary btn-block">Show</button>
      </div>
    </div>
  </div>
<% end %>

对如何设置有任何想法吗?

将您的索引方法替换为:

def index
  @incidenttypes = Incident.order(:incidenttype).distinct.pluck(:incidenttype)
  @incidents = if params[:search] && params[:search][:created_at].present?
                 @dayofweek = params[:search][:dayofweek]
                 start_date, end_date = params[:search][:created_at].split(' - ')
                 filters = { created_at: start_date..end_date }
                 [:dayofweek, :incidenttype].each do |filter|
                   next if params[:search][filter].blank?  
                   filters.merge!({ filter => params[:search][filter] } )
                 end
                 Incident.where(filters)
               else
                 Incident.all
               end
end