joseph.harding
joseph.harding

Reputation: 60

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:

<%= 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. Right now it looks like {2=>1, 3=>1, 1=>2008}

I want to show a date select input on the Edit View form field. 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?

Upvotes: 1

Views: 346

Answers (1)

spickermann
spickermann

Reputation: 107067

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.

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

Upvotes: 1

Related Questions