【问题标题】:rake db:seed doesn't workrake db:seed 不起作用
【发布时间】:2014-10-09 11:58:45
【问题描述】:

我正在为项目使用 hstore,并且我有一个迁移文件:

class CreateShippingCategories < ActiveRecord::Migration
  def change
    create_table :shipping_categories do |t|
      t.string  :name
      t.hstore  :size
      t.integer :price_transport
      t.integer :price_storage
      t.timestamps
    end
  end
end

默认情况下,我有 4 种类别,我决定在 seed.rb 文件中创建它们,如下所示:

shipping_categories = [
  [ "Small", {L: 40, B: 30, H: 22}, 700, 100],
  [ "Medium", {L: 60, B: 40, H: 32}, 900, 400],
  [ "Large", {L: 60, B: 52, H: 140}],
  [ "XX Large", {L: 200, B: 50, H: 200}]
]

shipping_categories.each do |name, size, price_transport, price_storage|
  ShippingCategory.where(name: name, size: size, price_transport: price_transport, price_storage: price_storage).first_or_create
end

但是当我尝试运行 rake db:seed 时,我得到了这个错误:

rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "size"
LINE 1: ... WHERE "shipping_categories"."name" = 'Small' AND "size"."L"...
                                                         ^
: SELECT  "shipping_categories".* FROM "shipping_categories"  WHERE "shipping_categories"."name" = 'Small' AND "size"."L" = 40 AND "shipping_categories"."price_transport" = 700 AND "shipping_categories"."price_storage" = 100  ORDER BY "shipping_categories"."id" ASC LIMIT 1

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: ruby-on-rails ruby hstore


    【解决方案1】:

    问题在于您在find_or_createfind 部分中查询的方式。我怀疑您要做的只是创建ShippingCategory(如果它不存在)。名字是独一无二的吗?如果是这样,您可以这样做:

    ShippingCategory.
      create_with(name: name, size: size, price_transport: price_transport, 
        price_storage: price_storage).
      find_or_create_by(name: name)
    

    有关详细信息,请参阅find_or_create_by 的文档。

    【讨论】:

      猜你喜欢
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2013-09-13
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      相关资源
      最近更新 更多