chrisjmendez / rails-associations

Simple relationships using Ruby on Rails and PostgreSQL.

Home Page:http://www.chrisjmendez.com/2016/12/21/rails-database-relationships/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rails Console

Destroy and rebuild the database with simple data

rails test:wipe

Enter Rails Console

rails c

Show which albums this Artist has

Artist.first.albums

Show the tracks from within an album

Artist.first.albums.first.tracks

Show the name of the song starting from Artist > Album > Track > Song

Artist.first.albums.first.tracks.first.song.title

Find the artist this songs belongs to

Song.first.artist

Get the album a song belongs to

Song.first.track.album

Get the tracks from a specific album

Album.second.tracks

Show the artist this album belongs to

Album.first.artist

Find the songs with the title "Sad But True"

Song.where("title = 'Sad But True'", Song.pluck(:title))

Find the songs with the text "sad" within the title

Song.where("title ILIKE ?", "%sad%")

Goals

  • An artist has many songs <> Songs belong to artists
  • An artist has many albums <> Albums belong to artists
  • An album has many tracks <> Tracks belong to albums <> Tracks have one song
  • Songs belong to many albums through tracks

I want to be able to:

  • Access an artist starting with a song
Song.first.artist
  • Access an album starting from a song
Song.find_by_title("Enter Sandman").tracks.first.album
  • Access a song starting from a artist
Artist.find_by_name("Metallica").albums.first.tracks.first.song
  • Access a track's order starting from a song
Song.first.albums.first.tracks.first.order
  • Access all the albums this song can be found on
Song.first.albums

Alternative Method

Song.first.tracks.album

Resources

About

Simple relationships using Ruby on Rails and PostgreSQL.

http://www.chrisjmendez.com/2016/12/21/rails-database-relationships/


Languages

Language:Ruby 87.4%Language:HTML 8.1%Language:CSS 2.7%Language:JavaScript 1.4%Language:CoffeeScript 0.5%