Skip to content

Instantly share code, notes, and snippets.

@stujo
Last active August 29, 2015 14:23
Show Gist options
  • Save stujo/e2b415c43e43326428f0 to your computer and use it in GitHub Desktop.
Save stujo/e2b415c43e43326428f0 to your computer and use it in GitHub Desktop.
Active Record Associations Overview

Active Record Associations

Overview

  • belongs_to
  • has_many
  • has_many :through
  • ActiveRecord::Relation
  • Remember: Models are not Migrations

Rails Guides

Our Model

  • Album belongs_to Artist
  • Artist has_many Albums
  • Track belongs_to Album
  • Albums has_many Tracks
  • Artist has_many Tracks :through Albums

Convention vs Configuration

Most of the time we can use the conventions Sometimes we need to customize

  • tablename <- Table Name
  • :foreign_key <- Foreign Key Column Name
  • :class_name <- Class of Associated Type

Option to Cut and Run

New Release...

PM: Artists sometimes help by producing an Album by a different Artist

  • What is the new relationship?
  • How could we express it in Active Record?
  • What changes do we need to make to the schema?
  • What is our work flow to change the schema for a published app?

Didn't Talk about

  • has_and_belongs_to_many Join table with no data

Helpful Code

  • Pro Tip: ActiveRecord::Relation#to_sql
  • ActiveRecord::Base.logger = Logger.new(STDOUT)
  • autoload :Artist, APP_ROOT.join('app', 'models', 'artist')
  • Migration Filename : Time.now.utc.strftime("%Y%m%d%H%M%S")
  • Look into https://github.com/janko-m/sinatra-activerecord
  • $ sqlite3 db/ar-relations.sqlite3
  • Track.new.methods - ActiveRecord::Base.instance_methods
  • new Artist: acdc = Artist.create(:name => 'AC/DC')
  • new Album: h2h = acdc.albums.create(title: 'Highway to Hell')
  • new Track: t2m = h2h.tracks.create(title: 'Touch Too Much')
  • Artist from Track: delegate :artist, :to => :album, :allow_nil => true
  • acdc.albums.to_sql
  • acdc.tracks.to_sql
  • Interesting: acdc = Artist.find_or_create_by(:name => 'AC/DC')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment