0

I have a simple search form in rails 3 that has two date fields. I'm having a problem getting these dates into my mysql db.

I've tried using the american_date gem, specifying date formats in my initializers, in the config/locales/en.yml file, and directly on the date on the date fields themselves. Currently, I'm setting the rails-approved date format in the view -

<%= f.text_field :depart_date, :value=> Date.today.strftime('%Y-%m-%d') %>

The dateformat in my DB is also YYYY-mm-dd, so things should be going smoothly.

The console tells me that the two date fields are both class = "Date"

I think I've found the disconnect. From the logs -

Started POST "/searches" for 127.0.0.1 at 2013-10-30 17:43:26 -0400
Processing by SearchesController#create as HTML
Parameters: {"utf8"=>"√","search"=>{"depart_date"=>"2013-10-30", 
"return_date"=>"2013-11-09"}
←[1m←[35m (0.0ms)←[0m  BEGIN
←[1m←[36mSQL (0.0ms)←[0m  ←[1mINSERT INTO `searches` (`depart_date`,`return_date`)
VALUES ('2013-30-10','2013-09-11')←[0m
←[1m←[35m (2.0ms)←[0m  COMMIT

Note that the month and day values are switched in the insert statement. How can I prevent this from happenening?

4
  • What happens when you use <%= f.text_field :depart_date, :value=> Date.today %> Commented Oct 31, 2013 at 3:54
  • Another option is trying Date.today.strftime('%m/%d/%Y') Commented Oct 31, 2013 at 3:56
  • The main thing is to let Rails do the translation for you, so use the minimal rails standard and go by examples in the api rather than mucking around with format I've learned from bitter experience. Commented Oct 31, 2013 at 3:56
  • Using :value=> Date.today shows the current date as "10/31/2013", but still tries to save it as 2013-31-10. I tried Date.today.strftime('%m/%d/%Y'), but it does the same, as well. Commented Oct 31, 2013 at 12:00

2 Answers 2

0

Most likely your timezone is not set correctly. Check which timezone your MySQL is using and which one your Rails is using.

You can try forcing a timezone in your rails app like this

class Application < Rails::Application
  config.time_zone = 'Eastern Time (US & Canada)'
end
Sign up to request clarification or add additional context in comments.

1 Comment

I set config.time_Zone = 'Eastern Time (US & Canada)', and also tried once with :local, and confirmed that the db instance is using SYSTEM time. It's still not saving the dates properly, though.
0

Set up a virtual attribute to translate between the text field and Date in the db. You can follow the railscasts to get these working -

#16 Virtual Attributes

#32 Time in Text Field

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.