【发布时间】:2020-07-06 04:51:32
【问题描述】:
我想为“created_at”创建一个范围搜索函数(在 created_at_from 和 created_at_to 之间)。 但是这个函数只实现 created_at_from 而不是 created_at_to,意思是如果 created_at_from: 12.01.2019 和 created_at_to: 01.01.2020 那么01.01.2020之后的数据也会显示出来。如何为日期范围创建搜索功能?
这是我的代码: 纸.rb
scope :search, -> (search_params) do
return if search_params.blank?
box_name(search_params[:box])
.created_at_from(search_params[:created_at_from])
.created_at_to(search_params[:created_at_to])
end
scope :box_name, -> (box) { where('box LIKE ?', "%#{box}%") if box.present? }
scope :created_at_from, -> (from) { where('? <= created_at', from) if from.present? }
scope :created_at_to, -> (to) { where('? <= created_at', to) if to.present? }
papers_controller.rb
def index
@search_params = papaer_search_params
@papers = Paper.search(@search_params).order(created_at: "DESC")
end
.
.
.
def paper_search_params
params.fetch(:search, {}).permit(:box, :created_at_from, :created_at_to)
end
index.html.erb
<%= form_with(scope: :search, url: index_papers_path, method: :get, local: true) do |f| %>
<%= f.label :box, "Box" %>
<%= f.text_field :box, value: @search_params[:box], class: 'form-control' %>
<span id='date-form' class='input-custom'>
<%= f.label :created_at, t('views.payment.date_from').html_safe + ':' %>
<%= f.text_field :created_at_from, {value: @search_params[:created_at_from], :class => 'form-control datepicker', :required => false} %> ~
<%= f.text_field :created_at_to, {value: @search_params[:created_at_to], :class => 'form-control datepicker', :required => false} %>
<%= submit_tag 'Search', class: "button" %>
【问题讨论】:
标签: ruby-on-rails ruby search datepicker