has_many/has_one vs belongs_to
class Book < ActiveRecord::Base
belongs_to :subject
end
class Subject < ActiveRecord::Base
has_many :books
end
Also, there is
has_one
just like has_many
inverse_of
Active Record provides the
:inverse_of
option so you can explicitly declare bi-directional associations:class Author < ApplicationRecord
has_many :books, inverse_of: 'writer'
end
class Book < ApplicationRecord
belongs_to :writer, class_name: 'Author', foreign_key: 'author_id'
end
a = Author.first
b = a.books.first
a.first_name == b.writer.first_name
=> true
a.first_name = 'David'
a.first_name == b.writer.first_name
=> true
dependent
If you set the
:dependent
option to::destroy
, when the object is destroyed,destroy
will be called on its associated objects.
:delete
, when the object is destroyed, all its associated objects will be deleted directly from the database without calling theirdestroy
method.
:destroy_async
: when the object is destroyed, anActiveRecord::DestroyAssociationAsyncJob
job is enqueued which will call destroy on its associated objects. Active Job must be set up for this to work.