单行has_many_through创建命令

时间:2014-05-21 13:55:21

标签: ruby-on-rails ruby activerecord

这些是我们的模型:

应用/模型/ 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)

是否可以将最后三行代码写为一个单一命令?怎么样?

2 个答案:

答案 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}])}