这些是我们的模型:
应用/模型/ ice_cream.rb
class IceCream < ActiveRecord::Base
has_many :ingredients
has_many :sundaes, through: :ingredients
end
应用/模型/ sundae.rb
class Sundae < ActiveRecord::Base
has_many :ingredients
has_many :ice_creams, through: :ingredients
end
应用/模型/ ingredient.rb
class Ingredient < ActiveRecord::Base
belongs_to :ice_cream
belongs_to :sundae
end
我们使用以下代码创建一个包含两个成分的新Sundae
:
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)
是否可以将最后三行代码写为一个单一命令?怎么样?
答案 0 :(得分:2)
你应该可以这样做:
Sundae.create(name: 'abc', ingredients: [Ingredient.create(ice_cream: IceCream.first, quantity: 2), Ingredient.create(ice_cream: IceCream.last, quantity: 1)])
当ActiveRecord
使用ingredients=
时,Sundae
会在has_many
类中添加一个ingredients
函数。
答案 1 :(得分:1)
这也应该有效:
Sundae.create(name: 'abc').tap{ |sundae| sundae.ingredients.create([{ice_cream: IceCream.first, quantity: 2}, {ice_cream: IceCream.first, quantity: 1}])}