播种数据库时状态为零

时间:2017-07-23 18:51:05

标签: ruby-on-rails ruby activerecord

我正在尝试使用种子文件播种我的Rails应用程序。一切正常,但订单对象的status属性始终为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

2 个答案:

答案 0 :(得分:3)

根据Documentation status列,必须是integer。我猜你有string,所以status总是重置为nil

答案 1 :(得分:2)

您的代码应该有效。我建议你先在Rails Console中试一试,看看是否有问题。这是我试图重现你的错误:

型号:

2.2.1 :004 > Order.statuses.keys.map(&:to_sym).sample
    => :confirmed

控制台输出:

Order.destroy_all
    1000.times do
    Order.create!(
        status: Order.statuses.keys.map(&:to_sym).sample
    )
end

更新:这是我的测试生成种子:

<强>分贝/ seeds.rb:

rake db:seed

执行2.2.1 :023 > Order.where('orders.status = ?', Order.statuses['confirmed']).size (0.4ms) SELECT COUNT(*) FROM "orders" WHERE (orders.status = 1) => 324 后,我进入控制台并检查生成数据的状态值:

2.2.1 :024 > Order.where('orders.status = ?', 
Order.statuses['draft']).size
   (0.3ms)  SELECT COUNT(*) FROM "orders" WHERE (orders.status = 0)
 => 340

这是另一种状态:

SELECT DISTINCT TRIM(name) FROM cities;