Rails Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

How does the development of any new rails app start?

A

rails new MY_APP

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does the app folders contain in a Rails project?

A

app
|–assets
|–controllers
|–models
|–views

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you build a link to the homepage of a Rails app?

A

<%= link_to “Home”, root_path %>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you build a link to an inner page in a Rails app?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does the development of any new rails app start?

A

rails new MY_APP

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you append elements of an array or another enumerable object to the end of an existing arrayin Ruby?

A

.concat

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How can you substract elements that in an array, from another array?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How is .take diffrent from .first in Ruby?

A

.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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can you sort a hash?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you process a csv file?

A

File.open(filename, “r”).each_line do |line|

codeblock

end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can you create in Ruby a Key Value pair with automatic incrementing of the value?

A

hash[key] += 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Get Jules Verne’s books

A

jules.books

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Get author with name=”Jules Verne”, store it in a variable: jules

A

jules = Author.find_by(name: “Jules Verne”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Add your favorite author (name)(class Authors) to the DB.

A

Author.create(name: “Paul Auster”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Write a migration to add a category column to the books table.

A

class AddCategoryToBooks < ActiveRecord::Migration[7.0]
def change
add_column :books, :category, :string
end
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

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

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the SQL query generated by #destroy:

doctor.id
# => 1
doctor.destroy

A

DELETE FROM doctors WHERE id = 1;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are the two SQL actions mapping Active Record method #save?

A

If #save is called on a new instance then it maps to INSERT INTO and UPDATE on a existing record.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

ActiveRecord Advanced
What are the most common validation types?

A

Presence, uniqueness (stand alone or using a scope), length (min or max), format (using Regexp).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Complete the following model with a 120-character minimum length validation on :description:

class Developer < ActiveRecord::Base
# TODO
end

A

class Developer < ActiveRecord::Base
validates :description, length: { minimum: 120 }
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What Active Record class method can you call when you want to delete all instances of a given model?

A

.destroy_all

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Write the migration to add an intern_id foreign key in patients table

A

class AddInternReferenceToPatients < ActiveRecord::Migration[7.0]
def change
add_reference :patients, :intern, foreign_key: true
end
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Complete the following migration file to add a zipcode column in the cities table:

class ??? < ActiveRecord::Migration[7.0]
def change
# TODO
end
end

A

class AddZipcodeToCities < ActiveRecord::Migration[7.0]
def change
add_column :cities, :zipcode, :string
end
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Write the migration to rename a column in your table?

A

class RenameOldColumnInTable < ActiveRecord::Migration[7.0]
def change
rename_column :table, :old_column_name, :new_column_name
end
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

In a 1:n relation between doctors and interns, write the migration to create the interns table?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

ActiveRecord Advanced
What are the 3 steps you should follow to properly modelize your data when conceiving your app?

A
  1. Draw the tables in kitt.lewagon.com/db
  2. Create the migrations
  3. Create the models

Don’t forget to strictly follow Active Record’s naming convention (table name lower_case plural, model name CamelCase singular)!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

ActiveRecord Advanced
Complete the following model with a regex validation on :email (/\A.@..com\z/ works just fine):

class Developer < ActiveRecord::Base
# TODO
end

A

class Developer < ActiveRecord::Base
validates :email, format: { with: /\A.@..com\z/ }
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Complete the following migration:

class RemoveZipcodeFromCities < ActiveRecord::Migration[7.0]
def change
# TODO
end
end

A

def change
remove_column :cities, :zipcode, :string
end

(remove_column :table, :column, :type)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

ActiveRecord Basics:
What’s the difference between ::find_by and ::where?

A

::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!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Give the generic syntax of a migration to add a column to a given table?

A

class AddColumnToTable < ActiveRecord::Migration[7.0]
def change
add_column :table, :column, :type
end
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What are the 2 files created by Rails’ model generator?

A

> The migration file to create corresponding table in the DB,
The model itself model_name.rb containing the class ModelName.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Write the code of the restaurants#show action

A

def show
@restaurant = Restaurant.find(params[:id])
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How can we refactor our form_with used in new.html.erb and edit.html.erb?

A

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 %>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the route for restaurants#update?

A

Rails.application.routes.draw do
[…]
patch “/restaurants/:id”, to: “restaurants#update”
[…]
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How can you revert a rails g model Something?

A

rails destroy model Something
# OR
rails d model Something

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is the route for restaurants#show (including the right prefix)?

A

Rails.application.routes.draw do
[…]
get “/restaurants/:id”, to: “restaurants#show”, as: :restaurant
[…]
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Write the code of the restaurants#new action

A

def new
@restaurant = Restaurant.new
# you need to give an empty shell to your form_with!
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is the route for restaurants#new (including the right prefix)?

A

Rails.application.routes.draw do
[…]
get “/restaurants/new”, to: “restaurants#new”, as: :new_restaurant
[…]
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Write a form_with to create or update a restaurant (name, address and rating)

A

<%= 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 %>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Write the code of the restaurants#update action

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Write the code of the restaurants#destroy action

A

def destroy
restaurant = Restaurant.find(params[:id])
restaurant.destroy
redirect_to restaurants_path, status: :see_other
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Write the code of the restaurants#create action

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What can you run in rails c to load last changes in your model(s) without exiting and re-entering in your console?

A

You can run reload!.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

How do you generate a model in Rails?

A

rails g model Restaurant name:string rating:integer #etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is the route for restaurants#destroy?

A

config/routes.rb
delete “/restaurants/:id”, to: “restaurants#destroy”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

How do you generate a subset of the 7 CRUD routes using resources?

A

With only:.

config/routes.rb
Rails.application.routes.draw do
resources :restaurants, only: [:index, :show]
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What are the 7 CRUD actions?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

How do you generate a migration in Rails?

A

rails g migration AddAddressToRestaurants address:string

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

Write the code of the restaurants#edit action

A

def edit
@restaurant = Restaurant.find(params[:id])
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What is the route for restaurants#create?

A

post “/restaurants”, to: “restaurants#create”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What rails db tasks do you know in Rails?

A

> 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What is the route for restaurants#edit (including the right prefix)?

A

get “/restaurants/:id/edit”, to: “restaurants#edit”, as: :edit_restaurant

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

What is the route for restaurants#index (including the right prefix)?

A

get “/restaurants”, to: “restaurants#index”, as: :restaurants

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

In a controller (or in a view), what handy object holds the data sent by your users through a form?

A

params.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

How can we skip generating tests when creating a new Rails app?

A

rails new MY_APP –skip-test

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

How do you build the path to a page of a Rails app, for example when using link_to?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

How do you define a route to a ‘contact’ static page with Rails?

A

Rails.application.routes.draw do
get ‘contact’ => ‘pages#contact’
# OR
get ‘contact’, to: ‘pages#contact’
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

What is the command allowing you to list your app’s routes with Rails?

A

rails routes

Prefix Verb URI Pattern Controller#Action
#contact GET /pages/contact pages#contact
# root GET /

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

What is the Rails action/view convention?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

Which information does rails routes display?

A

rails routes show you a list of your routes with details:

  • Prefix is the rails path prefix of the associated route
  • Verb is the HTTP verb of the route
  • URI Pattern is the path of the route
  • Controller#Action are targeted controller and method
62
Q

How do you build a link to an inner page in a Rails app?

A

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>

63
Q

How do you prevent a restaurant from being persisted in the DB without a name?

A

You must add validation to the model Restaurant:

app/models/restaurant.rb
class Restaurant < ApplicationRecord
validates :name, presence: true
end

64
Q

How do you define those RESTful routes:

GET /restaurants/:restaurant_id/reviews/new
POST /restaurants/:restaurant_id/reviews

A

You need to nest the resources:

config/routes.rb
Rails.application.routes.draw do
resources :restaurants do
resources :reviews, only: [:new, :create]
end
end

(It also defines the 7 canonical routes for the :restaurants. If you only want the index, add only: [:index] to that line)

65
Q

How do you define a route GET /restaurants/:id/chef with Rails?

A

You need to nest the route with member:

config/routes.rb
Rails.application.routes.draw do
resources :restaurants do
member do # member => restaurant id in URL
get ‘chef’ # RestaurantsController#chef
end
end
end

66
Q

Let’s say we have a validation on the presence of a name for restaurants.

Write the code of the restaurants#create action so that it renders the validation errors if there are any.

A

app/controllers/restaurants_controller.rb
class RestaurantsController < ApplicationController
def create
@restaurant = Restaurant.new(restaurant_params)
if @restaurant.save
redirect_to restaurant_path(@restaurant)
else
render :new, status: :unprocessable_entity
end
end

[…]

private

def restaurant_params
params.require(:restaurant).permit(:name, :address, :rating)
end
end

Don’t forget to pass status: :unprocessable_entity to respond with the 422 HTTP code.

67
Q

How do you define a route GET /restaurants/top with Rails?

A

How do you define a route GET /restaurants/top with Rails?

config/routes.rb
Rails.application.routes.draw do
resources :restaurants do
collection do # collection => no restaurant id in URL
get ‘top’ # RestaurantsController#top
end
end
end

68
Q

How do you add a validation on a model Restaurant to check if its rating is 0, 1, 2 or 3?

A

app/models/restaurant.rb

class Restaurant < ApplicationRecord
validates :rating, inclusion: { in: [0,1,2,3], allow_nil: false }
end

69
Q

How do you build this form with Rails?

<form>
<input></input>
<input></input>
<input></input>
</form>

A

with simple_form_for helper:

<%= simple_form_for [@restaurant, @review] do |f| %>
<%= f.input :content %>
<%= f.submit “add a review” %>
<% end %>

70
Q

How do you define image transformation with Cloudinary?

A

Inside the image call

<!-- app/views/products/show.html.erb -->

<%= cl_image_tag @product.photo.key, brightness: 30, radius: 20,
width: 150, height: 150, crop: :thumb, gravity: :face %>

71
Q

Which library can you use to easily handle file upload attached to a given model?

A

Active Storage

72
Q

Which crop modes do you know to transform images with Cloudinary?

A

Cloudinary offers various transformation options on images.

<!-- app/views/pages/home.html.erb -->

<%= cl_image_tag(“THE_IMAGE_ID_FROM_LIBRARY”, crop: :fill) %>

73
Q

<%= simple_form_for @product do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<% end %>
Which input do you have to add to this form to upload a Cloudinary/Active Storage photo?

A

<%= f.input :photo, as: :file %>

74
Q

How do you run pending migrations in your production environment?

A

heroku run rails db:migrate

75
Q

How do you push all secret variables to Heroku?

A

heroku config:set VARIABLE_NAME=value123
For example:

heroku config:set CLOUDINARY_URL=cloudinary://298522699261255:Qa1ZfO4syfbOC-*******8

76
Q

What DB related command was unnecessary with Rails new projects working with sqlite?

A

rails db:create, as development.sqlite file already existed in config/db.

77
Q

How do you display an image hosted by Cloudinary?

A

You need to use cl_image_tag helper:

<!-- app/views/pages/home.html.erb -->

<%= cl_image_tag(“THE_IMAGE_ID_FROM_LIBRARY”) %>
<!-- <img src="https://cloudinary.com/images/v1/AZERRT9876dfgh2345PO.jpg" alt="AZERRT9876dfgh2345PO"> -->

78
Q

What installation command do you need to run to get the Active Storage migrations?

A

rails active_storage:install # copies the migration files
rails db:migrate

79
Q

What can you type in your terminal if you don’t remember a heroku command?

A

heroku
Will print available heroku commands.

80
Q

How do you open a rails c in your production environment

A

heroku run rails c

81
Q

How do you create your app on Heroku?

A

With heroku create.
Depending on your users main location, you might want to specify the region where you want your app to be hosted. Default region is the US.

heroku create $YOUR_APP_NAME –region eu

82
Q

How do you open your website in your browser from your terminal?

A

heroku open

83
Q

After running heroku create, what will git remote -v return in your terminal (assuming you already have a remote repo on GitHub)?

A

It will return your GitHub remote (origin) and your Heroku remote (heroku).

heroku https://git.heroku.com/my-fancy-app.git (fetch)
heroku https://git.heroku.com/my-fancy-app.git (push)
origin git@github.com:MyGithubNickname/my-fancy-app.git (fetch)
origin git@github.com:MyGithubNickname/my-fancy-app.git (push)
You can now push your code on Heroku!

84
Q

How should you prefix a command in the terminal when it comes to your production environment?

A

heroku run rails c

Will open a console connected to your production environment.

85
Q

How can you create a new Rails project with a postgresql DB?

A

rails new $YOUR_APP_NAME –database=postgresql

86
Q

If you did not create the Heroku app yourself, how can you add a Heroku remote in order to push your code in production from your laptop?

A

heroku git:remote -a your-app-name

87
Q

app/models/product.rb
class Product < ApplicationRecord
has_one_attached :photo
end
How do you display the photo hosted by Cloudinary of @product?

A

<%= cl_image_tag @product.photo.key %>
<!-- <img src="https://cloudinary.com/images/v1/AZERRT9876dfgh2345PO.jpg" alt="AZERRT9876dfgh2345PO"> -->

88
Q

How can you check the logs of your app in production?

A

heroku logs –tail

89
Q

Which line of code do you need to add an attached file with Active Storage to a model?

A

app/models/product.rb
class Product < ApplicationRecord
has_one_attached :photo
# OR
has_many_attached :photos

# This is where you define the name of the attachment, it doesn’t necessarily have to be :photo / :photos!
end

90
Q

How do you push your master branch on Heroku?

A

git push heroku master

91
Q

Why do apps running on Heroku need an external service to store images uploaded by clients?

A

Heroku’s dyno file system is ephemeral so it is impossible to upload and store clients’ images. Everytime you git push to Heroku, a new “server” is dynamically created for you, and you lose all the files you might have created with the previous version on Hard drive. There’s no continuity there Learn more.

92
Q

What useful devise helpers do you know?

A

You can check if a user is currently logged in with user_signed_in? (returns a boolean).

You can catch the user currently signed in with current_user (returns an instance of User).

93
Q

How many controllers does devise use?

A

Devise uses 3 controllers:

RegistrationsController to handle CRUD on users,
SessionsController to handle sessions (logging in, logging out, …),
PasswordsController to handle forgotten password and password updates.
Don’t hesitate to run rails routes in your terminal to see their names and actions with your own eyes, files are not accessible in your project.

94
Q

How do you handle which pages can be seen without being logged in?

A

You should follow a allow-list approach. You force authentication for every pages by setting a before_action filter in your application_controller.rb.

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :authenticate_user!
end

Then you skip_before_action the actions you open to visitors in corresponding controller, for instance:

95
Q

Devise has many modules. Where do you handle the modules you want to include?

A

In user.rb.

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end

96
Q

How do you add a first_name field to your devise-generated User model?

A

First, you need to run a migration to add the first_name column in your users table in your DB:

rails g migration AddFirstNameToUsers first_name:string
Then, add a first_name field to the devise-generated view to make it available to the user in app/views/devise/registrations/new.html.erb).

Finally, don’t forget to update default Devise strong params by adding first_name in the keys.

97
Q

Devise comes with a lot of built-in views for the sign-in and sign-up pages, etc. If you want to edit them (to update them with customized elements or style), what do you need to do?

A

Run rails g devise:views in your terminal. Then you can edit the views in the folder app/views/devise.

98
Q

Let’s assume you’re working on an app with a Twitter connect and don’t want to force your users to add their email at sign up. How can you deactivate devise validations on :email and :password?

A

You can remove :validatable module in user.rb.

99
Q

How do you generate your User model using devise?

A

rails g devise User

100
Q

Which command can you run to generate a new Stimulus controller?

A

rails generate stimulus CONTROLLER_NAME will create a new controller.js file, prefixed by the name of the controller chosen.

101
Q

Which command can we run to import a package with importmaps?

A

We can run importmap pin $NAME_OF_THE_LIBRARY to pin a package to our project.

102
Q

With Turbo, what happens to the DOM when we click on a link?

A

For instance when we click on a link, it won’t reload the page but will replace the content of the page by the HTML response of that request.

103
Q

What is Turbo?

A

Turbo is a library to speed up navigation, pre-installed in our Rails 7 apps. It acts as if it was replacing the whole body of the page by the HTML of the response.

104
Q

Which Stimulus event listens to a form submit? Write an example of a data-action that would link the form submit to the send method of a insertResults controller.

A

We can listen to a form submit with the action submit. For instance, we could have a data-action=”submit->insertResults#send” in our form.

105
Q

Which gem do we use to build JSON responses?

A

We use jbuilder, which allows us to generate JSON structures easily while using conditionals, iterators or loops.

106
Q

Which method can we use in our controller to handle several formats of requests?

A

We can use respond_to and pass it a block with each format we want to handle (html, json, …).

107
Q

What do we use importmaps for?

A

Importmaps is a gem that allow us to import JavaScript libraries in a project.

108
Q

What is the connect method in Stimulus?

A

The connect method is called when the controller is instantiated. It will be executed when the controller appears in the DOM.

109
Q

How can you setup weights with pg_search_scope if you want results with the search term in the :title to appear before results with the search term in the :syllabus?

A

With pg_search, you can give a weight to a column with a letter:

class Movie < ApplicationRecord
# […]
include PgSearch
pg_search_scope :search_by_title_and_syllabus, {
against: {
title: “A”,
syllabus: “B”
}
}
end

110
Q

What’s a search results page from a CRUD point of view?

A

It’s a filtered index.

111
Q

How can we search:

in the movies :title and :syllabus columns, and
in the associated directors :first_name and :last_name columns?

A

class MoviesController < ApplicationController
def index
if params[:query].present?
sql_query = “ \
movies.title ILIKE :query \
OR movies.syllabus ILIKE :query \
OR directors.first_name ILIKE :query \
OR directors.last_name ILIKE :query \

@movies = Movie.joins(:director).where(sql_query, query: “%#{params[:query]}%”)
else
@movies = Movie.all
end
end
end

112
Q

pg_search full text search matches on whole words by default. How can you make it work for partial words?

A

By setting tsearch: { prefix: true } in the options:

class Movie < ApplicationRecord
# […]
include PgSearch
pg_search_scope :global_search, {
against: [ :title, :syllabus ],
using: {
tsearch: { prefix: true }
}
}
end

113
Q

How can we simply improve our search to be case insensitive and having the search term included in (vs. strictly equivalent to) the movie’s title?

A

By using PostgreSQL ILIKE keyword and % operator:

class MoviesController < ApplicationController
def index
if params[:query].present?
@movies = Movie.where(“title ILIKE ?”, “%#{params[:query]}%”)
else
@movies = Movie.all
end
end
end

114
Q

How do you keep the current search term as the value of the input in the results’ page using form_with?

For instance when the path is /movies?query=Superman, we want to display:

<form>
<input></input>
</form>

A

By setting the second argument of the corresponding text_field_tag to params[:query]:

<%= form_with url: movies_path, method: :get do %>
<%= text_field_tag :query, params[:query], class: “form-control” %>
<% end %>

115
Q

How can you search through an associated table with pg_search_scope?

A

With pg_search, you can search through an associated table by setting the associated_against option:

class Movie < ApplicationRecord
# […]
include PgSearch
pg_search_scope :global_search, {
against: [ :title, :syllabus ],
associated_against: {
director: [ :first_name, :last_name ]
}
}
end

116
Q

ILIKE does not work when a user types multiple terms. What PostgreSQL operator enables multiple terms search?

A

PostgreSQL @@ full text operator!

> Movie.where(“title @@ ?”, “Superman Batman”)
=> [#<Movie:0x00007fc9c8248f08
id: 2,
title: “Batman v Superman: Dawn of Justice”,
year: 2016,
[…]>]

117
Q

Write the plain HTML <form> that would trigger the following HTTP request:

GET ‘/movies?query=Superman’

A

The plain HTML form would be:

<form>
<input></input>
</form>

118
Q

@@ operator does not work if each term is not exactly in the columns browsed.

Which gem comes to the rescue if we want both multiple terms (@@) and ILIKE %term% features?

A

The pg_search gem!

119
Q

How do you simply tweak an index action to serve a search feature with a :query parameter?

A

By adding a conditional statement and using Active Record’s .where:

class MoviesController < ApplicationController
def index
if params[:query].present?
@movies = Movie.where(title: params[:query])
else
@movies = Movie.all
end
end
end

120
Q

Code the following form using Rails form_with helper (without simple_form):

<form>
<input></input>
</form>

A

<%= form_with url: movies_path, method: :get do %>
<%= text_field_tag :query, nil, class: “form-control” %>
<% end %>

121
Q

Where would you define your search parameters using the pg_search_scope method?

A

In the model!

122
Q

How many arguments should you pass to the pg_search_scope method? What’s their type?

A

The pg_search_scope method takes 2 arguments:

the first one is a Symbol and defines the name of the method you’ll call on your model to operate the search
the second one is a Hash to setup the search options
class Movie < ApplicationRecord
# […]
include PgSearch
pg_search_scope :search_by_title_and_syllabus, {
against: [ :title, :syllabus ] <– will lookup the search term in those columns
}
end

123
Q

How can we search both in the movies :title and :syllabus columns?

A

With the OR operator:

class MoviesController < ApplicationController
def index
if params[:query].present?
sql_query = “title ILIKE :query OR syllabus ILIKE :query”
@movies = Movie.where(sql_query, query: “%#{params[:query]}%”)
else
@movies = Movie.all
end
end
end

124
Q

Given the following :search_by_title_and_syllabus search:

class Movie < ApplicationRecord
# […]
include PgSearch
pg_search_scope :search_by_title_and_syllabus, {
against: [ :title, :syllabus ] <– will lookup the search term in those columns
}
end
Write the code calling this search from the controller:

A

class MoviesController < ApplicationController
def index
if params[:query].present?
@movies = Movie.search_by_title_and_syllabus(params[:query])
else
@movies = Movie.all
end
end
end

125
Q

Which pattern does Action Cable follow?

A

A Pub/Sub pattern, for publish / subscribe.

Clients subscribe to a channel, and the server publishes information in it, received by all subscribers.

126
Q

What protocol does Action Cable rely on?

A

WebSocket (WS in short)

127
Q

How do you install Action Cable in your Rails application?

A

The actioncable Ruby gem is already included in your Rails application as a dependency but the @rails/actioncable JavaScript package is not so you need to execute yarn add @rails/actioncable to install it.

128
Q

What is the execution flow when a user opens a chatroom in a browser?

A

1,The subscription creation request is called client-side
2.It triggers the subscribed method of the ChatroomChannel

From there on, the cable is connected between the client and the server on this chatroom’s channel.

129
Q

What is the execution flow when a new message is posted in a chatroom?

A
  1. The new message is pushed in the cable
  2. It triggers the received callback in all browsers connected to this chatroom
130
Q

Which JavaScript method is called when data is broadcast in the cable?

A

The received callback defined in the client subscription code:

this.subscription = createConsumer().subscriptions.create({ channel: “ChatroomChannel”, id: this.chatroomIdValue }, {
received(data) {
// this code is executed when data is broadcast in the cable from the server
}
});

131
Q

What are the 3 steps when you setup Action Cable?

A
  1. Generate the channel
  2. Setup the client subscriber with the received callback
  3. Broadcast data in the cable
132
Q

What is Action Cable?

A

Action Cable is a framework based on WebSocket to write real-time features in a Rails app.

133
Q

Which gem can you add to give CRUD access to users of your app?

A

You can add Rails admin.

134
Q

How can you differentiate classic users from admin users?

A

By adding an admin:boolean column in your users table:

rails g migration AddAdminToUsers admin:boolean
class AddAdminToUsers < ActiveRecord::Migration[7.0]
def change
add_column :users, :admin, :boolean, default: false
end
end

135
Q

How do you fix the N+1 queries problem?

A

By loading the children with the parent in the controller with includes:

@parent = Parent.includes(:children).find(params[:id])

136
Q

How do you setup a line chart with blazer?

A

With a SELECT SQL query on numerical values, grouped by a column of type date or datetime truncated by day, month, quarter or year:

SELECT
date_trunc(‘month’, purchased_at)::date,
COUNT(*)
FROM orders
GROUP BY 1;

137
Q

How do you setup authentication and authorization with blazer?

A

In the routes, with a lambda:

authenticate :user, ->(user) { user.admin? } do
mount Blazer::Engine, at: “blazer”
end

138
Q

How do you setup a graph with an input with blazer?

A

With a variable delimited with {}:

SELECT * FROM users WHERE gender = {gender}

139
Q

When does an N+1 occur?

A

When you have a one-to-many relationship between two models and you loop on the children in the view.

140
Q

Break down the N+1: where do the N and where does the 1 queries occur?

A

The 1 query occurs in the controller, when we fetch the parent. The N queries occur in the view, when we fetch each child in the loop.

141
Q

In which group of your Gemfile should you add Bullet?

A

In the group: :development as it’s a tool to help you in the development environment only.

142
Q

How do you setup a graph with a select with blazer?

A

With a smart variable setup in the config file:

smart_variables:
gender: “SELECT DISTINCT gender FROM users”

143
Q

How can you allow CRUD actions on a subset of tables only?

A

With the config.included_models option in the config/initializers/rails_admin.rb file:

config.included_models = [ “Seller”, “Product”, “User” ]

144
Q

How do you setup a graph with a time range with blazer?

A

With start_time and end_time variables:

SELECT * FROM ratings WHERE rated_at >= {start_time} AND rated_at <= {end_time}

145
Q

Which gem helps you break down the loading time of an HTTP request?

A

The rack-mini-profiler gem. It is a very helpful tool to improve your code’s performance.

146
Q

What does the respond_to method in Rails do?

A

It handles different response formats (such as HTML, JSON, XML) for a single controller action, allowing the action to respond appropriately based on the request format.

147
Q

How do you access query parameters in a Rails controller?

A

Using the params hash, e.g., params[:query].

148
Q

Explain the structure of a URL with query parameters.

A

Query parameters follow the ? character in a URL and are key-value pairs separated by &. For example: https://example.com/search?query=rails&sort=asc.

149
Q

How does respond_to do |format| work in a Rails controller?

A

It takes a block where different formats (like format.html, format.json) specify how to respond to requests of different content types.

150
Q

In the MoviesController, what does format.text { render partial: “movies/list”, locals: { movies: @movies }, formats: [:html] } do?

A

It renders the _list.html.erb partial with the @movies variable passed as a local variable, ensuring the partial is rendered in HTML format.

151
Q

How do you handle the presence of a query parameter in a Rails controller?

A

Using params[:query].present? to check if the parameter is provided and then perform actions based on its presence.

152
Q

How does Rails determine the format of the request in respond_to?

A

Rails checks the Accept header in the HTTP request or the format specified in the URL (e.g., /movies.json).