New model object through an association

陌路散爱 提交于 2019-12-21 12:41:23

问题


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.new() # NoMethodError: undefined method `new' for nil:NilClass

回答1:


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



来源:https://stackoverflow.com/questions/3821387/new-model-object-through-an-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!