DEV Community

Walktheworld
Walktheworld

Posted on

Active Record Associations

I am currently working on my first Ruby/Sinatra Application for my online software engineering program. I wanted to share what I learned about Active Record Associations and all the built in methods we get access to using it.

has_many

An instance of one class that owns many instances of another class. This class must pluralize the has many instance method to get access to all the instances it owns. A User has many recipes

class Actor < ActiveRecord::Base
    has_many :characters
end
Enter fullscreen mode Exit fullscreen mode
class Show < ActiveRecord::Base
    has_many :characters
end
Enter fullscreen mode Exit fullscreen mode

The has_many association gives us access to 17 methods

actors
actors<<(object, ...)
actors.delete(object, ...)
actors.destroy(object, ...)
actors=(objects)
actor_ids
actor_ids=(ids)
actors.clear
actors.empty?
actors.size
actors.find(...)
actors.where(...)
actors.exists?(...)
actors.build(attributes = {})
actors.create(attributes = {})
actors.create!(attributes = {})
actors.reload
Enter fullscreen mode Exit fullscreen mode

belongs_to

An instance that is owned by the has many class. We will state the belongs to method as singular to retrieve the relationship to the unique owner class. A Recipe belongs to one owner

class Character < ActiveRecord::Base
    belongs_to :actor
    belongs_to :show
end
Enter fullscreen mode Exit fullscreen mode

To ensure reference consistency, add a foreign key to the owner column of the owned table migration.

class CreateRecipes < ActiveRecord::Migration[6.1]
  def change
    create_table :characters do |t|
      t.belongs_to :actor
      t.belongs_to :show
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

The belongs_to association gives us access to 8 methods

character
character=(character)
build_character(attributes = {})
create_character(attributes = {})
create_character!(attributes = {})
reload_character
character_changed?
character_previously_changed?
Enter fullscreen mode Exit fullscreen mode

has_many through:

This creates a relationship bridge between two owner classes' and the owned/connecting class

class Show < ActiveRecord::Base
    has_many :characters
    has_many :actors, through: :characters
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)