ruby-on-rails 如何为created_at创建范围搜索函数

u7up0aaq  于 2023-05-23  发布在  Ruby
关注(0)|答案(1)|浏览(122)

我想为“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之后的数据。如何为日期范围创建搜索功能?
下面是我的代码: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" %>
n9vozmp4

n9vozmp41#

您的fromto查询是相等的,因此其中一个查询不能按预期工作。只需将它们更改为:

scope :created_at_from, -> (from) { where('created_at <= ?', from) if from.present? }
scope :created_at_to,   -> (to)   { where('? <= created_at', to  ) if to.present?   }

相关问题