Rails Flashcards
How does the development of any new rails app start?
rails new MY_APP
What does the app folders contain in a Rails project?
app
|–assets
|–controllers
|–models
|–views
How do you build a link to the homepage of a Rails app?
<%= link_to “Home”, root_path %>
How do you build a link to an inner page in a Rails app?
You need to use link_to with the correct path.
you can build the link:
<%= link_to “Contact”, contact_path %>
which results in:
<a>Contact</a>
How does the development of any new rails app start?
rails new MY_APP
How can you append elements of an array or another enumerable object to the end of an existing arrayin Ruby?
.concat
How can you substract elements that in an array, from another array?
array1 -= array2
In this example, array1 -= array2 removes elements from array1 that are also present in array2. So, after the operation, array1 contains only the elements that are unique to array1.
How is .take diffrent from .first in Ruby?
.first is specific for arrays to take the first object(s).
.take is more flexible because it works not only on arrays but also on other enumerable objects like database queries or generators and can also limit how many database entries you take for instance.
How can you sort a hash?
hash.sort_by { |key, value| -value }[0…num].to_h
The sort_by method is called on the counter hash, and it takes a block as an argument.
The -value inside the block negates each value, which effectively sorts the hash in descending order of values.
Since array indexing starts from 0, we need to use … so the correct number of elements is taken.
After selecting the top elements as a range from the sorted array, .to_h is called to convert this range into a hash.
How do you process a csv file?
File.open(filename, “r”).each_line do |line|
codeblock
end
How can you create in Ruby a Key Value pair with automatic incrementing of the value?
hash[key] += 1
What does this method do?
counter = Hash.new(0)
stop_words = load_stop_words(stop_words_filename)
File.open(filename, “r”).each_line do |line|
line.chomp.downcase.split(/\W+/).each do |word|
counter[word] += 1 unless stop_words.include? word
end
end
Initializes a hash counter with each new key as standard value 0.
- Loads a method for stop_words
- Opens a csv file and itrerrates over each line.
- removes the line break from the line, downcases it and splits it at non word characters.
- creates each word as key with the standard value of zero and increments its value unless it is a word that is in the stop_words array.
Get Jules Verne’s books
jules.books
Get author with name=”Jules Verne”, store it in a variable: jules
jules = Author.find_by(name: “Jules Verne”)
Add your favorite author (name)(class Authors) to the DB.
Author.create(name: “Paul Auster”)
Write a migration to add a category column to the books table.
class AddCategoryToBooks < ActiveRecord::Migration[7.0]
def change
add_column :books, :category, :string
end
end
Complete the following migrations to create your e-library database for title, year, foreig id, and another important element.
class CreateBooks < ActiveRecord::Migration[7.0]
def change
end
end
end
class CreateBooks < ActiveRecord::Migration[7.0]
def change
create_table :books do |t|
t.string :title
t.integer :year
t.references :author, foreign_key: true
t.timestamps
end
end
end
What is the SQL query generated by #destroy:
doctor.id
# => 1
doctor.destroy
DELETE FROM doctors WHERE id = 1;
What are the two SQL actions mapping Active Record method #save?
If #save is called on a new instance then it maps to INSERT INTO and UPDATE on a existing record.
ActiveRecord Advanced
What are the most common validation types?
Presence, uniqueness (stand alone or using a scope), length (min or max), format (using Regexp).
Complete the following model with a 120-character minimum length validation on :description:
class Developer < ActiveRecord::Base
# TODO
end
class Developer < ActiveRecord::Base
validates :description, length: { minimum: 120 }
end
What Active Record class method can you call when you want to delete all instances of a given model?
.destroy_all
Write the migration to add an intern_id foreign key in patients table
class AddInternReferenceToPatients < ActiveRecord::Migration[7.0]
def change
add_reference :patients, :intern, foreign_key: true
end
end
Complete the following migration file to add a zipcode column in the cities table:
class ??? < ActiveRecord::Migration[7.0]
def change
# TODO
end
end
class AddZipcodeToCities < ActiveRecord::Migration[7.0]
def change
add_column :cities, :zipcode, :string
end
end
Write the migration to rename a column in your table?
class RenameOldColumnInTable < ActiveRecord::Migration[7.0]
def change
rename_column :table, :old_column_name, :new_column_name
end
end
In a 1:n relation between doctors and interns, write the migration to create the interns table?
class CreateInterns < ActiveRecord::Migration[7.0]
def change
create_table :interns do |t|
t.string :first_name
t.string :last_name
t.references :doctor, foreign_key: true
t.timestamps
end
end
end
ActiveRecord Advanced
What are the 3 steps you should follow to properly modelize your data when conceiving your app?
- Draw the tables in kitt.lewagon.com/db
- Create the migrations
- Create the models
Don’t forget to strictly follow Active Record’s naming convention (table name lower_case plural, model name CamelCase singular)!
ActiveRecord Advanced
Complete the following model with a regex validation on :email (/\A.@..com\z/ works just fine):
class Developer < ActiveRecord::Base
# TODO
end
class Developer < ActiveRecord::Base
validates :email, format: { with: /\A.@..com\z/ }
end
Complete the following migration:
class RemoveZipcodeFromCities < ActiveRecord::Migration[7.0]
def change
# TODO
end
end
def change
remove_column :cities, :zipcode, :string
end
(remove_column :table, :column, :type)
ActiveRecord Basics:
What’s the difference between ::find_by and ::where?
::find_by returns the first record verifying the condition, whereas ::where returns every record verifying the condition, in an array.
Note that ::where always returns an array (even if there’s zero or one result), and ::find_by returns an instance or nil!
Give the generic syntax of a migration to add a column to a given table?
class AddColumnToTable < ActiveRecord::Migration[7.0]
def change
add_column :table, :column, :type
end
end
What are the 2 files created by Rails’ model generator?
> The migration file to create corresponding table in the DB,
The model itself model_name.rb containing the class ModelName.
Write the code of the restaurants#show action
def show
@restaurant = Restaurant.find(params[:id])
end
How can we refactor our form_with used in new.html.erb and edit.html.erb?
We can create a partial _form.html.erb in our views/restaurants folder and render it in our templates.
<!-- app/views/restaurants/new.html.erb -->
<%= render ‘form’, restaurant: @restaurant %>
<!-- app/views/restaurants/edit.html.erb -->
<%= render ‘form’, restaurant: @restaurant %>
What is the route for restaurants#update?
Rails.application.routes.draw do
[…]
patch “/restaurants/:id”, to: “restaurants#update”
[…]
end
How can you revert a rails g model Something?
rails destroy model Something
# OR
rails d model Something
What is the route for restaurants#show (including the right prefix)?
Rails.application.routes.draw do
[…]
get “/restaurants/:id”, to: “restaurants#show”, as: :restaurant
[…]
end
Write the code of the restaurants#new action
def new
@restaurant = Restaurant.new
# you need to give an empty shell to your form_with!
end
What is the route for restaurants#new (including the right prefix)?
Rails.application.routes.draw do
[…]
get “/restaurants/new”, to: “restaurants#new”, as: :new_restaurant
[…]
end
Write a form_with to create or update a restaurant (name, address and rating)
<%= form_with model: @restaurant do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :address %>
<%= f.text_field :address %>
<%= f.label :rating %>
<%= f.number_field :rating %>
<%= f.submit %>
<% end %>
Write the code of the restaurants#update action
def update
restaurant = Restaurant.find(params[:id])
restaurant.update(restaurant_params)
redirect_to restaurant_path(restaurant)
end
[…]
private
def restaurant_params
params.require(:restaurant).permit(:name, :address, :rating)
end
Write the code of the restaurants#destroy action
def destroy
restaurant = Restaurant.find(params[:id])
restaurant.destroy
redirect_to restaurants_path, status: :see_other
end
Write the code of the restaurants#create action
def create
@restaurant = Restaurant.new(restaurant_params)
@restaurant.save
redirect_to restaurant_path(@restaurant)
end
[…]
private
def restaurant_params
params.require(:restaurant).permit(:name, :address, :rating)
end
What can you run in rails c to load last changes in your model(s) without exiting and re-entering in your console?
You can run reload!.
How do you generate a model in Rails?
rails g model Restaurant name:string rating:integer #etc.
What is the route for restaurants#destroy?
config/routes.rb
delete “/restaurants/:id”, to: “restaurants#destroy”
How do you generate a subset of the 7 CRUD routes using resources?
With only:.
config/routes.rb
Rails.application.routes.draw do
resources :restaurants, only: [:index, :show]
end
What are the 7 CRUD actions?
index # Read all resources
show # Read one resource
new # display form for a resource creation
create # Create resource
edit # display form for a resource update
update # Update resource
destroy # Delete resource
How do you generate a migration in Rails?
rails g migration AddAddressToRestaurants address:string
Write the code of the restaurants#edit action
def edit
@restaurant = Restaurant.find(params[:id])
end
What is the route for restaurants#create?
post “/restaurants”, to: “restaurants#create”
What rails db tasks do you know in Rails?
> rails db:drop - Drops the database (lose all your data!)
rails db:create - Creates the database with an empty schema
rails db:migrate - Runs pending migrations on the database schema
rails db:seed - Runs seeds.rb file
rails db:rollback - Revert the last migration
rails db:reset - Drops database + replays all migration + runs seed
What is the route for restaurants#edit (including the right prefix)?
get “/restaurants/:id/edit”, to: “restaurants#edit”, as: :edit_restaurant
What is the route for restaurants#index (including the right prefix)?
get “/restaurants”, to: “restaurants#index”, as: :restaurants
In a controller (or in a view), what handy object holds the data sent by your users through a form?
params.
How can we skip generating tests when creating a new Rails app?
rails new MY_APP –skip-test
How do you build the path to a page of a Rails app, for example when using link_to?
Run rails routes in your terminal to know the prefix of the associated route then append _path to the prefix and Rails builds the path:
rails routes
Prefix Verb URI Pattern Controller#Action
#contact GET /pages/contact pages#contact
# root GET / pages#home
contact_path
# => ‘/pages/contact’
How do you define a route to a ‘contact’ static page with Rails?
Rails.application.routes.draw do
get ‘contact’ => ‘pages#contact’
# OR
get ‘contact’, to: ‘pages#contact’
end
What is the command allowing you to list your app’s routes with Rails?
rails routes
Prefix Verb URI Pattern Controller#Action
#contact GET /pages/contact pages#contact
# root GET /
What is the Rails action/view convention?
The Rails action/view convention links a controller’s action to a specific view through a naming convention:
app/controllers/pages_controller.rb
class PagesController < ApplicationController
def home
end
end