has_many/has_one vs belongs_to
class Book < ActiveRecord::Base
belongs_to :subject
end
class Subject < ActiveRecord::Base
has_many :books
endAlso, there is
has_one just like has_manyinverse_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
=> truedependent
If you set the
:dependent option to::destroy, when the object is destroyed,destroywill 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 theirdestroymethod.
:destroy_async: when the object is destroyed, anActiveRecord::DestroyAssociationAsyncJobjob is enqueued which will call destroy on its associated objects. Active Job must be set up for this to work.