Ruby on rails 通过create命令,单行有多个
这些是我们的模型: app/models/ice_cream.rbRuby 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
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}])}