我认为可以通过关联创建一个新的模型对象.
class Order < ActiveRecord::Base belongs_to :basket end class Basket < ActiveRecord::Base has_one :order end order = Order.new() basket = order.basket.new() # NoMethodError: undefined method `new' for nil:NilClass
解决方法
它是,但你的语法有点错误:
class Order < ActiveRecord::Base belongs_to :basket end class Basket < ActiveRecord::Base has_one :order end order = Order.new() basket = order.create_basket()
如果您不想立即保存篮子,请使用build_basket;如果关系是has_many:baskets,请使用order.baskets.create()和order.baskets.build()