我认为可以通过关联创建一个新的模型对象。
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
答案 0 :(得分:27)
确实如此,但你的语法有点不对劲:
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()