简体   繁体   English

在 Rails 中,将字符串从 date_select 转换为 Date

[英]In Rails, Convert string from date_select to Date

I have a string like this:我有一个这样的字符串:

{2=>1, 3=>1, 1=>2008}

It was generated from a select field like this:它是从 select 字段生成的,如下所示:

<%= user_record.date_select :response, {
                            order: [:month, :day, :year], 
                            prompt: { 
                              day: 'Select day', 
                              month: 'Select month', 
                              year: 'Select year' 
                            }, 
                            start_year: Date.today.year - 12, 
                            end_year: Date.today.year - 110
                          } %>

And stored as a string in the database.并作为字符串存储在数据库中。 (I can't change this to a date type, because it's user generated content). (我无法将其更改为日期类型,因为它是用户生成的内容)。

This causes 2 problems: I want to show a humanized version of the date on the Show view.这会导致 2 个问题: 我想在 Show 视图上显示日期的人性化版本。 Right now it looks like {2=>1, 3=>1, 1=>2008}现在看起来像 {2=>1, 3=>1, 1=>2008}

I want to show a date select input on the Edit View form field.我想在编辑视图表单字段中显示日期 select 输入。 Right now it errors with现在它错误

undefined method `year' for "{2=>1, 3=>1, 1=>2008}":String

I have tried splitting the string, and stripping characters, but is there a better solution in Ruby?我尝试过拆分字符串和剥离字符,但在 Ruby 中是否有更好的解决方案?

You could add a customer setter and getter method to your model to translate between the incoming hash from the view and the string type database column.您可以在 model 中添加一个客户设置器和获取器方法,以在来自视图的传入 hash 和字符串类型数据库列之间进行转换。

Something like this might work:像这样的东西可能会起作用:

def response
  Date.parse(super)
end

def response=(value)
  value = Date.new(value[1], value[2], value[3]) if value.is_a?(Hash)

  super(value.to_s)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM