首页 > 解决方案 > Rails:如何从搜索表单中获取日期

问题描述

所以,我有一个搜索表单,我试图从 url 中获取日期,但我没有得到它。

<%= form_with(url: "/flights", method: "get", local: true) do %>
<%= label_tag :from %>
<%= select_tag(:start_airport, options_for_select(@airport_options)) %> <br> <br>
<%= label_tag :to %>
<%= select_tag(:finish_airport, options_for_select(@airport_options)) %> <br> <br>
<%= label_tag :passengers %>
<%= select_tag(:passengers, options_for_select(@passengers)) %> <br> <br>
<%= select_tag(:date, options_for_select(@dates_options)) %> <br> <br>
<%= submit_tag("Search") %>

我想我必须改变日期,但是当我尝试

@flights = Flight.where(start_airport_id: params[:start_airport], finish_airport_id: params[:finish_airport], date: date: DateTime.strptime(params[:date], "%d %b  %H:%M"))

我没有将 nil 隐式转换为 String 错误。

航班控制器.rb

    def index
    @airport_options = Airport.all.map { |a| [a.code, a.id] }
    @passengers = (1..4).to_a
    @dates_options = Flight.order('date ASC').pluck(:date).map { |date| date.strftime("%d %b  %H:%M") }

    @flights = Flight.where(start_airport_id: params[:start_airport], finish_airport_id: params[:finish_airport], date: params[:date])
end

我数据库中的日期格式为“Sat, 02 May 2020 22:21:00 UTC +00:00”。

在网址中: http://localhost:3000/flights?start_airport=1&finish_airport=2&passengers=1&date=02+May++22%3A21&commit=Search

在调试器中:--- !ruby/object:ActionController::Parameters 参数:!ruby/hash:ActiveSupport::HashWithIndifferentAccess

日期:5月2日22:21

行动:索引允许:假

标签: ruby-on-railsruby

解决方案


推荐阅读