Neil Neil - 1 year ago 66
Ruby Question

Creating rails object with date attribute passed in "%m/%d/%Y" format

In my

I have a date picker that passes the selected date to the server in the format of
. Example: "05/30/2016".

Within the
action when I instantiate the object with the passed in params: Rails does not understand how to initialize the date attribute based on the format the date is passed in through the parameters, so it just sets the date attribute to nil.

class BlogsController < ApplicationController
def create
@blog = # does not understand how to initialize the some_date attribute based on the format it is passed in as, so it initializes the some_date attribute to nil
redirect_to some_path


def blog_params

This question suggests to create an initializer file that makes it so that rails will understand that format when it is passed into the parameters, but it did not work for me. It is still initializing the date to nil:

Date::DATE_FORMATS[:default] = "%m/%d/%Y"

I also tried this in that initializer file and there was some error with it so rails wouldn't even start the server:

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default] = '%m/%d/%Y'

Question: How can I make it so that when a date attribute is passed in the format of
: rails knows how to properly set that attribute and save the object successfully to the database?

Answer Source

I would think about a custom setter in the model.

Assuming your date attribute is named published_at the setter could look like:

def published_at=(date_string)
  write_attribute(:published_at, Date.strptime(date_string, '%m/%d/%Y'))