Skip to content

Instantly share code, notes, and snippets.

@NimaBoscarino
Created May 23, 2018 07:06
Show Gist options
  • Save NimaBoscarino/79e079477e3f0f64767235636b739d6e to your computer and use it in GitHub Desktop.
Save NimaBoscarino/79e079477e3f0f64767235636b739d6e to your computer and use it in GitHub Desktop.
require_relative 'app_config'
require_relative 'models/genre'
require_relative 'models/track'
AppConfig.establish_connection
genres = Genre.where(name: 'Rock')
song = Track.new name: "Genreless Song" # Our Track model says we need to have a genre, so we won't be able to save this.
puts song.save # returns false, since the save failed
puts song.save! # returns an object with all the errors. In this case, we see that Genre is required.
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
class Genre < ActiveRecord::Base
has_many :tracks
def sayHi # there's a method in genre, so we can call <Genre>.sayHi on any Genre instance.
puts "hello!"
end
end
class Track < ActiveRecord::Base
belongs_to :genre
validates :genre, presence: true # validation that says each track must have a genre
before_validation :make_uppercase # a callback being registered. make_uppercase runs before validation
after_save :send_email # another callback being registered
def lyrics
puts "Macarena!"
end
private # we put the callback methods inside of a private block, so these methods cannot be called on any Track instance
def make_uppercase
puts "MAKING UPPERCASE"
self.name = self.name.upcase
end
def send_email
nil # imagine there was some code here to send an email...
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment