Rake db: seed is not working

I am using hstore for a project and I have a migration file:

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

By default, I have 4 types of categories, and I decided to create them in the seeds.rb file as follows:

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

But when I try to run rake db: seed, I get this error:

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

Does anyone have any ideas how to solve this problem?

+4
source share
1 answer

The problem is how you request in findparts find_or_create. I suspect that you are trying to create only ShippingCategoryif it does not exist. Is the name unique? If so, you can do:

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

See the find_or_create_by documentation for more details .

+3
source

All Articles