Created
May 23, 2018 06:29
-
-
Save NimaBoscarino/635de50b054ed899d946f66d96ba2f69 to your computer and use it in GitHub Desktop.
W7D2 Ruby Lecture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require_relative 'app_config' | |
require_relative 'models/genre' | |
require_relative 'models/track' | |
AppConfig.establish_connection | |
genres = Genre.where(name: 'Rock') # get a collection that only has "Rock". .where always returns a collection of instances. | |
all_genres = Genre.all | |
genres.map do |genre| | |
puts genre.Name | |
genre.sayHi # we can call class methods for Genre | |
end | |
song = Track.new name: "Cool new song", genre: genres[0] | |
song.save # Insert into DB | |
Track.create name: "Another Cool Song", genre: genres[0] # immediately creating and inserting a song into the DB |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_record' | |
require 'active_support/all' | |
module AppConfig | |
DATABASE = 'chinook' | |
DATABASE_PATH = File.absolute_path("#{DATABASE}.db", File.dirname(__FILE__)) | |
def self.establish_connection | |
puts "Connecting to database '#{DATABASE_PATH}'" | |
ActiveRecord::Base.establish_connection( | |
adapter: 'sqlite3', | |
database: DATABASE_PATH | |
) | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source 'https://rubygems.org' | |
gem 'sqlite3' | |
gem 'activerecord' | |
gem 'activesupport' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Genre < ActiveRecord::Base | |
has_many :tracks | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Track < ActiveRecord::Base | |
belongs_to :genre | |
def lyrics | |
puts "Macarena!" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment