OOP Flashcards
Write the migration to rename a column in a table?
class RenameOldColumnInTable < ActiveRecord::Migration
def change
rename_column :table, :old_column_name, :new_column
end
end
What is a database query?
A DB query is a connection with the DB to read, create, update or delete records.
Complete the following model with a presence and uniqueness validation on :github_nickname
Class Developer < ActiveRecord::Base
validates :github_nickname, presence: true, uniqueness: true
end
What is the SQL query generated by destroy ------------------ doctor.id # => 1 doctor.destroy
This deletes one record in the table doctors.
How do you run a pending migrations?
$ rake db:migrate
How would you modelize a n:n relation between the following models:
class Post < ActiveRecord::Base end
class Category < ActiveRecord::Base end
class CreateCategoriesPosts < ActiveRecord::Migration
create_table :categories_posts do |t|
t.references :post, index: true
t.references :category, index: true
t.timestamps null: false
end
end
———————
And using through in your associations instructions in your models classes:
———————–
class Post < ActiveRecord::Base
has_many :categories_posts
has_many :categories, through: :categories_posts
end
class Category < ActiveRecord::Base
has_many :categories_posts
has_many :posts, through: :categories_posts
end
How can we add a a column to a table thanks to a migration?
class AddNewColumntoTable < ActiveRecord::Migration
def change
add_column :table, :new_column, :format
end
end
———————
If you name properly your migration class AddColumnToTable, Rails will autocomplete the code inside the change method
Write the migration to add an intern_id foreign key in patients table
class AddInternReferenceToPatiens < ActiveRecord::Migration
def change
add_reference :patiens, :intern, index: true
end
end
——————
Note the second argument :intern and not :intern_id
SELECT * FROM doctors WHERE specialty LIKE “%surgery”;
This query returns all doctors having specialty ending with “surgery”(note the %)
What symbol is used in a SQL query to get all columns?
SELECT * FROM TABLE
What is the SQL keyword to join two tables in a query?
JOIN…ON
SELECT * FROM first_table
JOIN second_table ON second_table.id = first_table.second_table_id;
Complete the following model with a regex validation on :email
Class Developer < ActiveRecord::Base
validates :email, format: { with: /\A.@..com\z/ }
end
How do you retrieve a specific record of a given ActiveRecord model?
By calling .find(id) on your model
or
By calling .find_by(attribute: value) if you don’t know the id
Consider the model Doctor, assuming you already created a DB with doctors tables, how would you add a new doctor in your DB?
dr_house = Doctor.new(name: “greg”)
dr_house.save
You start a new project, what is the next step following the user’s stories writing and mockups drawing, and before writing any line of code?
Project steps: > user's stories > mockups > db schema >> Start coding