searching records between start date and end dates for ransack
With https://github.com/dangrossman/bootstrap-daterangepicker you can do date range search with:
= search_form_for q, url: orders_path, builder: SimpleForm::FormBuilder do |f|
= f.input :daterange , input_html: {value: "#{q.date_gteq.to_s} - #{q.date_lteq.to_s}"}
= f.input :date_gteq, as: :hidden
= f.input :date_lteq, as: :hidden
:coffee
$ ->
$('#q_daterange').daterangepicker
format: "YYYY-MM-DD"
startDate: $('#q_date_gteq').val()
endDate: $('#q_date_lteq').val()
ranges:
'This Week': [moment().startOf('week'), moment().endOf('week')],
'Next Week': [moment().add('week', 1).startOf('week'), moment().add('week', 1).endOf('week')]
, (start, end, label) ->
$('#q_date_gteq').val start.format("YYYY-MM-DD")
$('#q_date_lteq').val end.format("YYYY-MM-DD")
.on 'apply.daterangepicker', -> $('#order_search').submit()
You could make a custom predicate.
In my view I have a ransack search field like
= f.text_field :request_date_between, class: 'daterange'
That will send a date to the controller like
'2015-10-01 to 2015-10-31'
then in my down and dirty ransack.rb initializer I have;
Ransack.configure do |config|
config.add_predicate 'between',
arel_predicate: 'between',
formatter: proc { |v| v.split(' to ') },
type: :string
end
module Arel
module Predications
def between other
gteq(other[0]).and(lt(other[1]))
end
end
end
to make between
predicate recognize local timezone, in ransack.rb
initializer...
Ransack.configure do |config|
config.add_predicate 'between',
arel_predicate: 'between',
formatter: proc { |v| Range.new(*v.split(' to ').map { |s| Time.zone.parse(s) }) },
type: :string
end
No need to overwrite Arel::Predications#between
.
(This works only on datetime column type.)