开发者

New model object through an association

开发者 https://www.devze.com 2023-01-18 05:41 出处:网络
I thought it was possible to create a new model object through an association. class Order < ActiveRecord::Base

I thought it was possible to create a new model object through an association.

class Order < ActiveRecord::Base
  belongs_to :basket
end

class Basket < ActiveRecord::Base
  has_one :order
end

order = Order.new()
basket = order.basket.ne开发者_如何学Cw() # NoMethodError: undefined method `new' for nil:NilClass


It is, but your syntax is a little wrong:

class Order < ActiveRecord::Base
  belongs_to :basket
end

class Basket < ActiveRecord::Base
  has_one :order
end

order = Order.new()
basket = order.create_basket()

Use build_basket if you don't want to save the basket immediately; if the relationship is has_many :baskets instead, use order.baskets.create() and order.baskets.build()

0

精彩评论

暂无评论...
验证码 换一张
取 消