4
date = Date.today     
query = "insert into custom_reports(name,description,created_at) values(#{report_name}, #{report_content}, #{date})"
ActiveRecord::Base.connection.execute(query);

it inserts

0000-00-00 00:00:00

So thought of going the mysql timestamp way. Is it possible to do?

1
  • check the db and the field type. Commented Sep 12, 2013 at 9:41

6 Answers 6

2

This should work

query = "insert into custom_reports(name,description,created_at) values('#{report_name}', '#{report_content}', '#{Time.now}')"
Sign up to request clarification or add additional context in comments.

Comments

0

Try, changing

date = Date.today

to

date = Time.now

Apart from the above I tend to not use variables that may or may not accidentally be a keyword (especially when I am not sure), so instead of naming variable as date, I would use d

4 Comments

2013-09-12 00:00:00 stores just the date, when used Date.today.
What's your db column type? Is it Date or DateTime?
Field name - created_at, Type - datetime
I can't read stuff like date = Time.now. Either it's a time or it's a date. Also, Time.current would cover more edge cases.
0

Why do you write that SQL manually? Thats is more complicated and insecure, because you do not escape the strings in the query. On the other side ActiveRecord will take care of the created_at column.

I would prefer to have a basic model for that:

class CustomReport < ActiveRecord::Base
end

CustomRepor.create!(name: report_name, description: report_content)

1 Comment

I agree with you, but link this wasn't solved, so I had to write using mysql manually.
0

Mysql "Date" type columns should use

Date.now

Mysql "Time" type columns should use

Time.now

Mysql "DateTime" type columns have to use

DateTime.now

Comments

0
  1. I had to find out what is the data format on my created_at field

    rails db
    select created_at from users;
    
    +---------------------+
    | created_at          |
    +---------------------+
    | 2017-12-12 00:51:19 |
    | 2017-12-12 00:51:20 |
    | 2017-12-12 00:51:22 |
    | 2017-12-12 00:51:23 |
    +---------------------+
    
  2. Then I have to run the raw query according to the format I'm using.

    date = Time.now.strftime("%Y-%m-%d %H:%M:%S")
    
    query = "insert into custom_reports(name,description,created_at) values(#{report_name}, #{report_content}, #{date})"
    ActiveRecord::Base.connection.execute(query);
    

Comments

-1

Try Changing the timestamp to date time format:

Time.at(1335437221) 

convert 2012-04-26 12:47:01 +0200

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.