Reputation: 3699
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?
Upvotes: 4
Views: 7259
Reputation: 161
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 |
+---------------------+
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);
Upvotes: 0
Reputation: 670
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
Upvotes: 0
Reputation: 11
Try Changing the timestamp to date time format:
Time.at(1335437221)
convert 2012-04-26 12:47:01 +0200
Upvotes: -1
Reputation: 106802
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)
Upvotes: 0
Reputation: 5111
This should work
query = "insert into custom_reports(name,description,created_at) values('#{report_name}', '#{report_content}', '#{Time.now}')"
Upvotes: 2
Reputation: 11234
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
Upvotes: 0