ac360
ac360

Reputation: 7835

Rails Postgres - Datetime value won't save into Datetime column

My model has a datetime attribute (Postgres) and I am attempting to create a new record via form submission in my Rails app.

The form I'm submitting contains a text_field for that datetime attribute. It submits the datetime in the below format as a param:

"expires"=>"07/17/2013 12:35:26 PM"

However, once it enters into the first line of code within the Create action of my Model...

def create
  @special_deal = SpecialDeal.new(params[:special_deal])

...most of the time, @special_deal.expires will = nil. Only rarely, does it work.

I can't figure out why this is happening. I'm guessing it has something to do with including the AM or PM within the datetime value, but Im not sure.

The params includes the expires value every time:

    @_params    
{"utf8"=>"✓", "authenticity_token"=>"cl1SwnHOum8d/kiGnwkDsamG5IMbmdnoeFvlY11KpKc=", "special_deal"=>{"title"=>"", "provider"=>"", "description"=>"", "deal_price"=>"", "conditions"=>"", "expires"=>"07/27/2013 14:23:59", "excerpt"=>"", "original_price"=>"", "phone_number"=>"", "street"=>"", "city"=>"", "postal_code"=>"", "state"=>"", "country"=>""}, "commit"=>"Create Special deal", "action"=>"create", "controller"=>"special_deals"}

But @special_deal does not:

    @special_deal   
#<SpecialDeal id: nil, man_servant_id: nil, category: "", title: "", excerpt: "", description: "", original_price: nil, deal_price: nil, provider: "", product_link: "", conditions: "", phone_number: "", street: "", city: "", postal_code: "", state: "", country: "", public: true, created_at: nil, updated_at: nil, expires: nil, image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil>

Upvotes: 1

Views: 3805

Answers (2)

Amarnath Krishnan
Amarnath Krishnan

Reputation: 1263

It will be set obviously nil because params[:special_deal][:expires] does not hold a valid format. No matter whether your form has a text_field or string. What matters is the format you are sending, while creating new special deal. Your code will work if you manipulate the expire field and form the standard date time format. No matter whether its a string object or datetime object.

The standard DB format for datetime is YYYY-MM-DD HH:MM:SS

So before creating a new special deal you have to manipulate the expire

"expires"=>"07/17/2013 12:35:26 PM"

"expires"=>"2013-07-17 12:35:26"

Dont forget to take Meridiem into account while manipulating it. This will solve your problem.

Upvotes: 2

George
George

Reputation: 118

Try putting these in the create method:

logger.error params[:special_deal].class
logger.error params[:special_deal].to_datetime

or use the debugger to investigate them.

It seems that it doesn't get converted properly to datetime.

You will get a clear hint after this.

Upvotes: 2

Related Questions