Antarr Byrd
Antarr Byrd

Reputation: 26081

Status nil when seeding database

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.

seed.rb

Order.destroy_all
1000.times do
  Order.create!(
    product: products.sample,
    customer: Customer.all.sample,
    status: Order.statuses.keys.map(&:to_sym).sample
  )
end

order.rb

class Order < ApplicationRecord
  belongs_to :product
  belongs_to :customer

  enum status: [:draft, :confirmed, :canceled]
end

Upvotes: 0

Views: 261

Answers (2)

Gabriel Gomes
Gabriel Gomes

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

Igor Drozdov
Igor Drozdov

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

Related Questions