Reputation: 26081
I'm trying to seed my Rails application using a seed file. Everything works, except the status
attribute of my Order object that's always nil
.
Order.destroy_all
1000.times do
Order.create!(
product: products.sample,
customer: Customer.all.sample,
status: Order.statuses.keys.map(&:to_sym).sample
)
end
class Order < ApplicationRecord
belongs_to :product
belongs_to :customer
enum status: [:draft, :confirmed, :canceled]
end
Upvotes: 0
Views: 261
Reputation: 348
Your code should work. I recommend you to give a try in the Rails Console first, to see if there is something wrong. Here is what i got trying to reproduce your error:
Model:
class Order < ApplicationRecord
enum status: [:draft, :confirmed, :canceled]
end
Console output:
2.2.1 :004 > Order.statuses.keys.map(&:to_sym).sample
=> :confirmed
UPDATE: Here is my test generating seeds:
db/seeds.rb:
Order.destroy_all
1000.times do
Order.create!(
status: Order.statuses.keys.map(&:to_sym).sample
)
end
After execute rake db:seed
i went to the console and checked status values of the generated data:
2.2.1 :023 > Order.where('orders.status = ?',
Order.statuses['confirmed']).size
(0.4ms) SELECT COUNT(*) FROM "orders" WHERE (orders.status = 1)
=> 324
Here is another status:
2.2.1 :024 > Order.where('orders.status = ?',
Order.statuses['draft']).size
(0.3ms) SELECT COUNT(*) FROM "orders" WHERE (orders.status = 0)
=> 340
Upvotes: 2
Reputation: 15045
According to Documentation status
column must be an integer
. I guess you have string
instead, so status
always resets to nil
.
Upvotes: 3