Ruby-on-rails 如何从 Rails 中的 date_select 或 select_date 获取日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13605598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:05:44  来源:igfitidea点击:

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

ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.2params

提问by at.

Using select_dategives me back a params[:my_date]with year, monthand dayattributes. How do get a Date object easily? I'm hoping for something like params[:my_date].to_date.

使用select_date给了我一个params[:my_date]with year,monthday属性。如何轻松获取 Date 对象?我希望有类似的东西params[:my_date].to_date

I'm happy to use date_selectinstead as well.

我也很乐意使用date_select它。

回答by joofsh

Using date_select gives you 3 separate key/value pairs for the day, month, and year respectively. So you can pass them into Date.newas parameters to create a new Date object.

使用 date_select 分别为您提供 3 个单独的日、月和年的键/值对。因此,您可以将它们Date.new作为参数传入以创建新的 Date 对象。

An example date_select returned params for an Eventmodel:

示例 date_select 返回Event模型的参数:

"event"=>
 {"name"=>"Birthday",
  "date(1i)"=>"2012",
  "date(2i)"=>"11",
  "date(3i)"=>"28"},

Then to create the new Dateobject:

然后创建新Date对象:

event = params[:event]
date = Date.new event["date(1i)"].to_i, event["date(2i)"].to_i, event["date(3i)"].to_i

You may instead decide to wrap this logic in a method:

您可以改为决定将此逻辑包装在一个方法中:

def flatten_date_array hash
  %w(1 2 3).map { |e| hash["date(#{e}i)"].to_i }
end

And then call it as date = Date.new *flatten_date_array params[:event]. But this is not logic that truly belongs in a controller, so you may decide to move it elsewhere. You could even extend this onto the Dateclass, and call it as date = Date.new_from_hash params[:event].

然后将其称为date = Date.new *flatten_date_array params[:event]. 但这不是真正属于控制器的逻辑,因此您可能决定将其移至其他地方。您甚至可以将其扩展到Date类上,并将其称为date = Date.new_from_hash params[:event].

回答by Vassilis

Here is another one:

这是另一个:

# view
<%= date_select('event', 'date') %>

# controller
date = Date.civil(*params[:event].sort.map(&:last).map(&:to_i))

Found at http://kevinlochner.com/use-rails-dateselect-without-an-activerecord

http://kevinlochner.com/use-rails-dateselect-without-an-activerecord找到

回答by Dhanabal

Here is the another one

这是另一个

Date.civil(params[:event]["date(1i)"].to_i,params[:event]["date(2i)"].to_i,params[:event]["date(3i)"].to_i)

回答by I0Result

Here is another one for rails 5:

这是 Rails 5 的另一个:

module Convert
  extend ActiveSupport::Concern

  included  do
    before_action :convert_date
  end

  protected

  def convert_date
    self.params = ActionController::Parameters.new(build_date(params.to_unsafe_h))
  end

  def build_date(params)
    return params.map{|e| build_date(e)} if  params.is_a? Array

    return params unless params.is_a? Hash

    params.reduce({}) do |hash, (key, value)|
      if result = (/(.*)\(\di\)\z/).match(key)
        params_name = result[1]
        date_params = (1..3).map do |index|
          params.delete("#{params_name}(#{index}i)").to_i
        end
        hash[params_name] =  Date.civil(*date_params)
      else
        hash[key] = build_date(value)
      end

      hash
    end
  end
end

You need to include it to your controller or application_controller.rb:

您需要将它包含到您的控制器或 application_controller.rb 中:

class ApplicationController < ActionController::Base
  include Convert
end

回答by Ryan Lue

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 Dateto DateTime); and
  2. it extracts a date from a set of paramseven when those params are populated with many other key-value pairs.
  1. 它没有明确地命名PARAM键xxx(1i)xxx(3i)(因此可以简单地通过改变进行修改,以捕捉小时和分钟DateDateTime); 和
  2. params即使这些参数填充了许多其他键值对,它也会从一组中提取日期。

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

params是格式的散列{ xxx(1i): '2017', xxx(2i): 12, xxx(3i): 31, ... }date_keyxxx目标日期参数的公共子字符串。

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.

我选择将它作为 的类方法ApplicationRecord,而不是作为 的实例辅助方法ApplicationController。我的推理是在 ActiveRecord 实例化器(Model.new)中存在类似的逻辑来解析从 Rails 表单传入的日期。

回答by Radu Cugut

With the date_select example @joofsh's answer, here's a "one liner" I use, presuming the date field is called start_date:

使用 date_select 示例@joofsh 的答案,这是我使用的“一个班轮”,假设日期字段被称为start_date

ev_params = params[:event]

date = Time.zone.local(*ev_params.select {|k,v| k.to_s.index('start_date(') == 0 }.sort.map {|p| p[1].to_i})

回答by Luis Flores

Or simply do this:

或者干脆这样做:

your_date_var = Time.parse(params[:my_date])