[Rails] Associations between models

Tags
Rails
Engineering
Created
Oct 7, 2023 04:46 AM
Edited
Oct 6, 2023
Description
has_many/has_one/belongs_to/inverse_of/dependent

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 their destroy method.
  • :destroy_async: when the object is destroyed, an ActiveRecord::DestroyAssociationAsyncJob job is enqueued which will call destroy on its associated objects. Active Job must be set up for this to work.

Related Articles