pingu
pingu

Reputation: 8827

New model object through an association

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

Upvotes: 10

Views: 16290

Answers (1)

Chowlett
Chowlett

Reputation: 46667

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

Upvotes: 34

Related Questions