我有一个搜索表单,用于搜索具有3个字段的事件模型:incidenttype
,dayofweek
和created_at
。在我的 incidents.index 方法中,检查是否存在搜索参数。然后根据created_at
范围等过滤结果。我将如何设置它,以便如果dayofweek
和incidenttype
参数为空或为空,则将不会在查询中使用它们过滤?本质上,如果未选择任何选项,则不使用这些参数,而仅使用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"> </label>
<button type="submit" class="btn btn-secondary btn-block">Show</button>
</div>
</div>
</div>
<% end %>
是否有任何关于设置的想法?
答案 0 :(得分:0)
将索引方法替换为:
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