Neil Neil - 6 months ago 15
Ruby Question

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

In my

_form.html.erb
I have a date picker that passes the selected date to the server in the format of
%m/%d/%Y
. Example: "05/30/2016".

Within the
create
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.
Example:

#blogs_controller.rb
class BlogsController < ApplicationController
def create
@blog = Blog.new(blog_params) # 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
@blog.save
redirect_to some_path
end

private

def blog_params
params.require(:blog).permit(:some_date)
end
end


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:

#initializers/date_format.rb
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
%m/%d/%Y
: rails knows how to properly set that attribute and save the object successfully to the database?

Answer

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'))
end
Comments