0

I am dynamically updating the underlying model by passing the parameters from the posted form to the model like this:

@model.assign_attributes(params[:model])

I have a date coming in along with the rest of the post data in the format mm/dd/yyyy. Ruby appears to be parsing this date as if it is in the format dd/mm/yyyy, as far as I can tell. So, when I enter a date of 4/15/2014, for instance, the model fails to save because the month 15 does not exist (I assume, in reality I am just told that the date field is required).

How can I configure Ruby to parse my dates as mm/dd/yyyy?

Josh M.
  • 26,437
  • 24
  • 119
  • 200

1 Answers1

1

Use the strptime method for date and supply the format.

Date.strptime("4/15/2014","%m/%d/%Y")
#=> #<Date: 2014-04-15 ((2456763j,0s,0n),+0s,2299161j)>

You will probably have to specify a call back like before_update if you want the conversion to happen in the model. e.g.

class YourModel < ActiveRecord::Base


  before_update :format_date


  def format_date
    date_field = Date.strptime(date_field,'%m/%d/%Y')
  end
end
engineersmnky
  • 25,495
  • 2
  • 36
  • 52
  • The controller isn't aware of the underlying model. It is a generic base class that is doing the saving. So I want to set this format globally. – Josh M. Apr 17 '14 at 16:28
  • I cannot find a way to do this.(Not to say there isn't one) but the controller need not be aware of the model. The Model just needs to be aware of the input format so that it can change it prior to saving. – engineersmnky Apr 17 '14 at 16:57
  • Ended up "fixing" the `:when` param upon post using `strpdate`. Thanks. – Josh M. Apr 18 '14 at 22:48