ruby-on-rails - rake 数据库 :seed doesn't work

标签 ruby-on-rails ruby hstore

我正在为项目使用 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

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

最佳答案

问题是您在 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的文档了解更多信息。

关于ruby-on-rails - rake 数据库 :seed doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25331670/

相关文章:

ruby-on-rails - 没有路由匹配 [GET] "/auth/facebook"in ruby​​ on rails 4

ruby-on-rails - 与 attr_accessor 相比,ActiveRecord 如何定义方法?

ruby-on-rails - 如何使用 ActiveRecord 按书籍数量对作者进行排序?

ruby - 声明后分配哈希值

python - 在 Python 中使用 psycopg2 将 PostgreSQL hstore 作为 OrderedDict 返回

python - Django "ValueErrror: could not find common ancestor of {migrations}"

node.js - 将 Sequelize/ORM 与 Postgres 扩展类型(如 LTREE 和 HSTORE)一起使用

ruby-on-rails - 如何从字符串末尾获取数字

ruby-on-rails - 如何从 Ruby 1.8.7 中的 utf-8 字符串中获取第 i 个字符?

ruby-on-rails - Rails 5 - 如何将 Controller 中整个 jsonb postgres 列的参数列入白名单?