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
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.
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.
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? 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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With