以下是我们的模型:
应用程序/型号/冰淇淋.rb
class IceCream < ActiveRecord::Base
has_many :ingredients
has_many :sundaes, through: :ingredients
end
app/型号/sundae.rb
class Sundae < ActiveRecord::Base
has_many :ingredients
has_many :ice_creams, through: :ingredients
end
应用程序/型号/成分.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)
是否可以将最后三行代码作为一个命令编写?怎么用?
最佳答案
你应该能够做到:
Sundae.create(name: 'abc', ingredients: [Ingredient.create(ice_cream: IceCream.first, quantity: 2), Ingredient.create(ice_cream: IceCream.last, quantity: 1)])
当您为
ActiveRecord
使用ingredients=
时,asSundae
将在has_many
类中添加一个函数ingredients
。关于ruby-on-rails - 单行has_many_through创建命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23785348/