rake db:seed无法正常运行

4

我正在使用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种类别,我决定像这样在seeds.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

有没有人有什么想法来解决这个问题?
1个回答

3
问题在于您在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的文档以获取更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接