Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 31, 2022 05:45 pm GMT

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 :charactersend
class Show < ActiveRecord::Base    has_many :charactersend

The has_many association gives us access to 17 methods

actorsactors<<(object, ...)actors.delete(object, ...)actors.destroy(object, ...)actors=(objects)actor_idsactor_ids=(ids)actors.clearactors.empty?actors.sizeactors.find(...)actors.where(...)actors.exists?(...)actors.build(attributes = {})actors.create(attributes = {})actors.create!(attributes = {})actors.reload

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 :showend

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  endend

The belongs_to association gives us access to 8 methods

charactercharacter=(character)build_character(attributes = {})create_character(attributes = {})create_character!(attributes = {})reload_charactercharacter_changed?character_previously_changed?

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: :charactersend

Original Link: https://dev.to/walktheworld/active-record-associations-15go

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To