通过关联的新模型对象

时间:2010-09-29 12:02:54

标签: ruby-on-rails activerecord associations

我认为可以通过关联创建一个新的模型对象。

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

1 个答案:

答案 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()