我正在尝试在加载页面时显示所有项目,如果选择了日期(使用materializecss datepicker),则仅显示项目的日期范围。显示所有项目很简单,因为我只需要做@all_requests = Request.all,但我花了两个晚上尝试各种方法,如form_for和form_tag等。目前使用下面的代码,由于默认日期,它只显示今天的项目。今天,但如果我删除默认值它会给出一个nil错误,我想因为日期尚未被选中...
Index.html.erb
<%= form_tag requests_path, method: :get do %>
<%= text_field_tag 'search[date_from]', @search.date_from, placeholder: 'From date', class: 'datepicker' %>
<%= text_field_tag 'search[date_to]', @search.date_to, placeholder: 'To date', class: 'datepicker' %>
<%= submit_tag 'Search', class: 'btn waves-effect waves-light formbttn' %>
<% end %>
<div class="row">
<% @all_requests.each do |request| %>
...
Request.search.rb
class RequestSearch
attr_reader :date_from, :date_to
def initialize(params)
params ||= {}
date_from = parsed_date(params[:date_from], Date.today.to_s)
date_to = parsed_date(params[:date_to], Date.today.to_s)
end
def scope
Request.where(:date => 'date_from'..'date_to')
end
def parsed_date(date_string, default)
Date.parse(date_string)
rescue ArgumentError, TypeError
default
end
end
Requests_controller.rb
def index
# if params[:search] == nil
# @all_requests = Request.all
# else
@search = RequestSearch.new(params[:search])
@all_requests = @search.scope
end
Materialisecss DOM
<input type="text" name="" id="search_date_from" value="2017-08-13"
placeholder="From date" class="datepicker picker__input" readonly=""
tabindex="-1" aria-haspopup="true" aria-expanded="false"
aria-readonly="false" aria-owns="search_date_from_root">
答案 0 :(得分:0)
class RequestSearch
attr_reader :date_from, :date_to
# use keyword args instead
def initialize(date_from: nil, date_to: nil, **kwargs)
# You need to use `@` to set instance vars
@date_from = parsed_date(date_from)
@date_to = parsed_date(date_to)
end
def scope
Request.where(date: date_from..date_to)
end
# reduce the arity by setting the default in the method
# definition
def parsed_date(date_string, default = Date.today.to_s)
Date.parse(date_string)
rescue ArgumentError, TypeError
default
end
end