How to get a Date from date_select or select_date in Rails?

后端 未结 7 1321
小鲜肉
小鲜肉 2020-11-30 04:05

Using select_date gives me back a params[:my_date] with year, month and day attributes. How do get a Date ob

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 04:27

    I use the following method, which has the following benefits:

    1. it doesn't have to explicitly name param keys xxx(1i) through xxx(3i) (and thus could be modified to capture hour and minute simply by changing Date to DateTime); and
    2. it extracts a date from a set of params even when those params are populated with many other key-value pairs.

    params is a hash of the format { xxx(1i): '2017', xxx(2i): 12, xxx(3i): 31, ... }; date_key is the common substring xxx of the target date parameters.

    def date_from_params(params, date_key)
      date_keys = params.keys.select { |k| k.to_s.match?(date_key.to_s) }.sort
      date_array = params.values_at(*date_keys).map(&:to_i)
      Date.civil(*date_array)
    end
    

    I chose to place this as a class method of ApplicationRecord, rather than as an instance helper method of ApplicationController. My reasoning is that similar logic exists within the ActiveRecord instantiator (i.e., Model.new) to parse dates passed in from Rails forms.

提交回复
热议问题