Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 907
pingu Avatar asked Sep 29 '10 12:09

pingu


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is Has_and_belongs_to_many?

As far as I can remember, has_and_belongs_to_many gives you a simple lookup table which references your two models. For example, Stories can belong to many categories. Categories can have many stories.

What is a polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


1 Answers

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

like image 112
Chowlett Avatar answered Sep 21 '22 15:09

Chowlett