New model object through an association

14,771

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

Share:
14,771
pingu
Author by

pingu

Updated on July 02, 2022

Comments

  • pingu
    pingu almost 2 years

    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
    
  • pingu
    pingu over 13 years
    Thanks Chris for your reply, out of interest i tried basket = order.basket.new() when the relationship is has_many :baskets, and it worked fine. Its all very confusing.
  • gertas
    gertas over 13 years
    It may work, but I'm not sure if order.basket collection will contain your newly created object, which means you can save order and have all child objects autosaved and referenced to order (without specifying it in parameters).