【问题标题】:How to create range search function for created_at如何为 created_at 创建范围搜索功能
【发布时间】: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


    【解决方案1】:

    您的from 和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?   }
    

    【讨论】:

    • 太棒了!非常感谢,斯派克曼!!我只更改为scope :created_at_from, -&gt; (from) { where('? &lt;= created_at', from) if from.present? } scope :created_at_to, -&gt; (to) { where('created_at &lt;= ?', to) if to.present? },它正在工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    相关资源
    最近更新 更多