Skip to content

Instantly share code, notes, and snippets.

@krokrob
Created July 30, 2019 16:19
Show Gist options
  • Save krokrob/9928f49501e5a6faddea0478ffd4193e to your computer and use it in GitHub Desktop.
Save krokrob/9928f49501e5a6faddea0478ffd4193e to your computer and use it in GitHub Desktop.
# Q8 write DB query with Ruby
# mapping between model and table
# mapping instance of model and a row in a table
# mapping instance variable and columns of a table
# ORM
# Q9 A ruby file which alter db schema structure (no data)
# ex: table, column
# Q10
class CreateAuthors < ActiveRecord::Migration[5.1]
def change
create_table :authors do |t|
t.string :name
t.timestamps null: false
end
end
end
class CreateBooks < ActiveRecord::Migration[5.1]
def change
create_table :books do |t|
t.string :title
t.integer :publishing_year
t.references :author, foreign_key: true
t.timestamps null: false
end
end
end
class CreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
t.string :email
t.timestamps null: false
end
end
end
class CreateReadings < ActiveRecord::Migration[5.1]
def change
create_table :readings do |t|
t.date :date
t.references :book, foreign_key: true
t.references :user, foreign_key: true
t.timestamps null: false
end
end
end
# Q11
class AddCategoryToBooks < ActiveRecord::Migration[5.1]
def change
add_column :books, :category, :string
end
end
# Q12
class Author < ActiveRecord::Base
has_many :books
validates :name, presence: true
end
class Book < ActiveRecord::Base
belongs_to :author
has_many :readings
end
class User < ActiveRecord::Base
has_many :readings
has_many :books, through: :readings
end
class Reading < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
# Q13
#1. Add your favorite author to the DB
Author.create(name: "Sir Arthur Conan Doyle")
#2. Get all authors
Author.all
#3. Get author with id=8
Author.find(8)
#4. Get author with name="Jules Verne", store it in a variable: jules
jules = Author.find_by(name: 'Jules Verne')
#5. Get Jules Verne's books
jules.books
#6. Create a new book "20000 Leagues under the Seas", it's missing # in the DB. Store it in a variable: twenty_thousand
twenty_thousand = Book.new(title: "20000 Leagues under the Seas")
#7. Add Jules Verne as this book's author
twenty_thousand.author = jules
#8. Now save this book in the DB!
twenty_thousand.save
# The end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment