belongs_to
has_many
has_many
:through
ActiveRecord::Relation
- Remember: Models are not Migrations
- Album
belongs_to
Artist - Artist
has_many
Albums - Track
belongs_to
Album - Albums
has_many
Tracks - Artist
has_many
Tracks:through
Albums
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
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?
has_and_belongs_to_many
Join table with no data
- 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')