Association Flashcards
How to add belongs_to association?
belongs_to :user
How to add has_many association?
has_many :dogs
How belongs_to works inside?
# belongs_to :user # something like this
define_method :user do User.find(self.user_id) end
How has_many works inside?
# has_many :dogs # something like this
define_method :dogs do
Dog.where(user_id: self.id)
end
How to destroy all associations record together with a parent record?
has_many :dogs, dependent: :destroy
How to not destroy (set parent_id to nil) all associations record together with a parent record?
has_many :dogs, dependent: :nullify
How to make belong_to association optional?
belongs_to :user, optional: true
What is polymorphic association? Any examples?
“with polymorphic associations, a model can belong to more than one other model, on a single association”.
class Cat < ApplicationRecord # can belongs_to only one of them belongs_to :human belongs_to :zoo belongs_to :restaurant belongs_to :streat
# why do we need to write all? let’s use polymorphic
belongs_to :owner, polymorphic: true # and this model has field owner_id and owner_type # for example owner_id=1 owner_type="Human" end
How to create a polymorphic association?
class Appointment < ApplicationRecord belongs_to :sick_animal, polymorphic: true end
class Cat < ApplicationRecord has_many :appointments, as: :sick_animal end
class Dog < ApplicationRecord has_many :appointments, as: :sick_animal end
How to add belongs_to association with another class?
belongs_to :user, class_name: ‘Cat’
# Dog.create(user: Cat.last) -> works # Dog.create(user: User.last) -> doesn't work
How to add belongs_to association with a ‘where’ condition?
class Dog < ApplicationRecord belongs_to :user, -> { where(status: true) } end
It doesn’t return a user with a false condition for a dog.
How to create a record through has_many clause? ( 2 ways)
user has_many dogs
- User.last.dogs.create
- User.last.dogs «_space;Dog.create
What is the difference between delete_all and destroy_all?
- delete_all doesn’t destroy the association, only nullify them
- destroy_all delete association as well
How to add where condition to has_many association?
class User < ApplicationRecord has_many :live_dogs, -> { where(alive: true) }, class_name: 'Dog' has_many :dead_dogs, -> { where(alive: false) }, class_name: 'Dog' end
What are the main differences between has_and_belongs_to_many and has_many through?
- has_and_belongs_to_many - implicitly creates only join table for you.
- has_many through - explicitly creates a join table and a model for you.