Ruby on rails 通过create命令,单行有多个

Ruby on rails 通过create命令,单行有多个,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,这些是我们的模型: app/models/ice_cream.rb class IceCream < ActiveRecord::Base has_many :ingredients has_many :sundaes, through: :ingredients end class Sundae < ActiveRecord::Base has_many :ingredients has_many :ice_creams, through: :ingredient

这些是我们的模型:

app/models/ice_cream.rb

class IceCream < ActiveRecord::Base
  has_many :ingredients
  has_many :sundaes, through: :ingredients
end
class Sundae < ActiveRecord::Base
  has_many :ingredients
  has_many :ice_creams, through: :ingredients
end
class Ingredient < ActiveRecord::Base
  belongs_to :ice_cream
  belongs_to :sundae
end

是否可以将最后三行代码作为一个命令编写?如何做?

您应该能够做到:

Sundae.create(name: 'abc', ingredients: [Ingredient.create(ice_cream: IceCream.first, quantity: 2), Ingredient.create(ice_cream: IceCream.last, quantity: 1)])
由于
ActiveRecord
将在
Sundae
类中添加一个函数
components=
,当您为
配料使用
时,这也应该起作用:

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

非常感谢你!工作完美。
Sundae.create(name: 'abc').tap{ |sundae| sundae.ingredients.create([{ice_cream: IceCream.first, quantity: 2}, {ice_cream: IceCream.first, quantity: 1}])}