Skip to content

Instantly share code, notes, and snippets.

@NimaBoscarino
Created May 23, 2018 06:29
Show Gist options
  • Save NimaBoscarino/635de50b054ed899d946f66d96ba2f69 to your computer and use it in GitHub Desktop.
Save NimaBoscarino/635de50b054ed899d946f66d96ba2f69 to your computer and use it in GitHub Desktop.
W7D2 Ruby Lecture
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
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
source 'https://rubygems.org'
gem 'sqlite3'
gem 'activerecord'
gem 'activesupport'
class Genre < ActiveRecord::Base
has_many :tracks
end
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