lumpy
lumpy

Reputation: 98

Single line has_many_through create command

These are our models:

app/models/ice_cream.rb

class IceCream < ActiveRecord::Base
  has_many :ingredients
  has_many :sundaes, through: :ingredients
end

app/models/sundae.rb

class Sundae < ActiveRecord::Base
  has_many :ingredients
  has_many :ice_creams, through: :ingredients
end

app/models/ingredient.rb

class Ingredient < ActiveRecord::Base
  belongs_to :ice_cream
  belongs_to :sundae
end

We use the following code to create a new Sundae with two ingredients:

IceCream.create(name: 'chocolate')
IceCream.create(name: 'vanilla')

Sundae.create(name: 'abc')
Sundae.first.ingredients.create(ice_cream: IceCream.first, quantity: 2)
Sundae.first.ingredients.create(ice_cream: IceCream.last, quantity: 1)

Is it possible to write the last three lines of code as one single command? How?

Upvotes: 2

Views: 41

Answers (2)

arndttouby
arndttouby

Reputation: 226

This should work, too:

Sundae.create(name: 'abc').tap{ |sundae| sundae.ingredients.create([{ice_cream: IceCream.first, quantity: 2}, {ice_cream: IceCream.first, quantity: 1}])}

Upvotes: 1

Saurabh
Saurabh

Reputation: 73589

You should be able to do:

Sundae.create(name: 'abc', ingredients: [Ingredient.create(ice_cream: IceCream.first, quantity: 2), Ingredient.create(ice_cream: IceCream.last, quantity: 1)])

as ActiveRecord will add a function ingredients= in the Sundae class when you use has_many for ingredients.

Upvotes: 2

Related Questions