I want to create a range search function for "created_at" (between created_at_from and created_at_to). But this function realizes only created_at_from but not created_at_to, means if created_at_from: 12.01.2019 and created_at_to: 01.01.2020 then the data after 01.01.2020 is also shown. How can I create a search function for the date range?
here is my code: paper.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" %>
Your from
and to
queries are equal, therefore one of them doesn't work as expected. Just change them to:
scope :created_at_from, -> (from) { where('created_at <= ?', from) if from.present? }
scope :created_at_to, -> (to) { where('? <= created_at', to ) if to.present? }