Aleksandrus
Aleksandrus

Reputation: 1754

Rails 4 error when seeding a has_many

I have a FlavorPizza scaffold and a SizePizza scaffold. I need to set the price of a flavor of a pizza based on it's size (the price of a small pizza is different from a large one). So, I created a PricePizza model, whose migration has :flavor_pizza_id, :size_pizza_id and :price attributes.

I'd like to, when I create/edit a FlavorPizza object, to pass a :price_pizza params, just like that

FlavorPizza.create({
    name: 'Muzzarela',
    price_pizzas:[
        {size_pizzas_id: 1, price:'9.99'},
        {size_pizzas_id: 2, price:'12.99}
    ]
})

I tried using has many through, but I keep getting errors. undefined method unscoped

Here is my code:

price_pizza migration:

create_table :price_pizzas do |t|
  t.integer :size_pizzas_id
  t.integer :flavor_pizzas_id

  t.decimal :price, :precision => 5, :scale => 2

  t.timestamps null: false
end

price_pizza.rb

class PricePizza < ActiveRecord::Base
    has_many :flavor_pizzas

    belongs_to :size_pizza
    belongs_to :flavor_pizza
end

flavor_pizza.rb

class FlavorPizza < ActiveRecord::Base
    has_many :price_pizzas

    accepts_nested_attributes_for :price_pizzas
end

size_pizza.rb

class SizePizza < ActiveRecord::Base
    has_many :price_pizzas
end

seeds.rb

SizePizza.create([{name: 'Small', diameter: '5.5', pieces: 3}])
FlavorPizza.create([{name: 'Muzzarela', description: 'test description', price_pizzas_attributes: [{size_pizzas_id: 1, price: '9.99'}]}])
#PricePizza.create(size_pizzas_id: 1, flavor_pizzas_id: 1, price: '10')

Upvotes: 1

Views: 85

Answers (1)

Ian Selby
Ian Selby

Reputation: 3241

This may not directly answer your question, but this is generally how I approach seeds:

size = SizePizza.where(name: 'Small').first_or_create(diameter: '5.5', pieces: 3)
flavor = FlavorPizza.where(name: 'Muzzarela').first_or_create(...)
flavor.price_pizzas.create(price: '9.99') # you could also see if the price exists if desired

This will prevent you from duplicating data on seeds, accomplish what you're looking to do, and prevent future issues if you add any unique constraints.

Also, for example, if you wanted to create multiple prices, you could always enhance with a loop:

%w(9.99 12.99 18.99).each { |price| flavor.price_pizzas.create(price: price) }

Upvotes: 1

Related Questions