[英]Rails multiple search parameters and defaults
我有一個搜索表單來搜索事件模型3個字段: incidenttype
, dayofweek
和created_at
。 在我的events.index方法中,我檢查是否存在搜索參數。 然后篩選基於該結果created_at
范圍等我將如何設置此所以,如果dayofweek
和incidenttype
PARAMS是空或空白,將不只是在查詢過濾器使用它們? 本質上,如果未選擇任何選項,則不使用這些參數,而僅使用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 %>
關於如何進行設置有任何想法嗎?
將索引方法替換為:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.