Simulate a timestamp in seeds.rb

I want to populate the database with sample data, and for some reason I also want to simulate created_at . This is my seeds.rb:

 9.downto(1) do |i| product = Product.new(price: 99.99) product.created_at = i.days.ago, product.save! end 

In the database, the result of rake db:seed as follows:

---- 2012-03-03 16:50:30.316886000 Z- 1

when i need

2012-03-03 16:50:30.316886000 Z- 1

How to avoid these ---- characters as a result?

(db: sqlite3)

update: I just found that when I use product.created_at = i.days.ago , the product.created_at = i.days.ago in the callback ( before_save ) is Array : [date_value, 1] . Therefore i can use

 before_save { self.created_at = self.created_at[0] } 

and then the value in the database will be correct (without ---- ), but using callbacks doesn't seem like a good way.

+4
source share
1 answer

The problem is this line:

 product.created_at = i.days.ago, 

You need to get rid of the trailing comma, so you end up with an array for created_at . Fix it and you can get rid of the before_save .

Edit: the reason you get --- because any ORM that you use is trying to serialize the array and turn it into YAML.

+4
source

Source: https://habr.com/ru/post/1400745/


All Articles