belongs_tohas_manyhas_many:throughActiveRecord::Relation- Remember: Models are not Migrations
- Album
belongs_toArtist - Artist
has_manyAlbums - Track
belongs_toAlbum - Albums
has_manyTracks - Artist
has_manyTracks:throughAlbums
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_manyJoin 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.sqlite3Track.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_sqlacdc.tracks.to_sql- Interesting:
acdc = Artist.find_or_create_by(:name => 'AC/DC')