Week 1 Questions Flashcards

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

what does update_attributes do?

A

The update_attributes method accepts a hash of attributes, and on success performs both the update and the save in one step (returning true to indicate that the save went through). Note that if any of the validations fail, such as when a password is required to save a record, the call to update_attributes will fail. If we need to update only a single attribute, using the singular update_attribute bypasses this restriction:
» user.update_attribute(:name, “El Duderino”)
=> true
» user.name
=> “El Duderino”

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

how would you find a user or any other model by specific attributes like and email or username?

A

User.find_by(email: “mhartl@example.com”)

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

how do you develop in the rails console without making any changes to the application?

A

rails console –sandbox

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

what do migrations do?

A

Migrations provide a way to alter the structure of the database incrementally, so that our data model can adapt to changing requirements.

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

how do you write a named route?

A
#original route name: 
get 'static_pages/help'
#named route name 
get  '/help', to: 'static_pages#help'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what are the 3 types of assets and how are they used?

A
  • app/assets: assets specific to the present application
  • lib/assets: assets for libraries written by your dev team
  • vendor/assets: assets from third-party vendors
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

why use instance variables?

A

they are automatically available in the views and they can be used throughout a class

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

what is a difference between single quotes and double quotes?

A

There’s an important difference, though; Ruby won’t interpolate into single-quoted strings:
» ‘#{foo} bar’ # Single-quoted strings don’t allow interpolation
=> “#{foo} bar”

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

how do you save changes on a branch and then merge them with the master?

A
$ git add -A
$ git commit -m "Finish static pages"
$ git checkout master
$ git merge static-pages
$ git push
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

explain this ruby idiom: a||=b

A

a =b when a == false

otherwise a remains unchanged

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

What is a Module? Can you tell me the difference between classes and modules?

A

Modules are about providing methods that you can use across multiple classes - think about them as “libraries” (as you would see in a Rails app). Classes are about objects; modules are about functions.

For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.

You might also use a module when you have shared methods across multiple apps (again, the library model is good here).

modules serve as mechanisms for namespaces

modules provide as a mechanism for multiple inheritance via mixins and cannot be instantiated like classes can

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

String vs Symbol

A

Symbols are immutable: Their value remains constant.

Multiple uses of the same symbol have the same object ID and are the same object compared to string which will be a different object with unique object ID, every time.

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

What is a callback?

A

Callbacks are methods that get called at certain moments of an object’s life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

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

Should a callback be public?

A

It is considered good practice to declare callback methods as protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.

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

What is the difference between private and protected?

A
  • protected methods can be called by any instance of the defining class or its subclasses.
  • private methods can be called only from within the calling object. You cannot access another instance’s private methods directly.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you display all errors for a user model?

A

user.errors.full_messages

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

What should be the maximum length for an email attribute and why?

A

Maximum length of strings for many databases is 255

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

How do you enforce uniqueness at the model level?

A
class User < ApplicationRecord
  validates :name, uniqueness: true
end
19
Q

How do you enforce uniqueness at the database level?

A

create a database index on the desired column and then require that the index be unique.

create a migration
example: rails generate migration add_index_to_users_email
#go to migration and add below
add_index :users, :email, unique: true
rails db:migrate
20
Q

Why would you add an index to an email address attribute?

A

it prevents a full-table scan when finding users by email address

21
Q

What 3 points of functionality does the method has_secure_password have when added to a model?

A
  1. The ability to save a securely hashed password_digest attribute to the database
  2. A pair of virtual attributes (password and password_confirmation), including presence validations upon object creation and a validation requiring that they match
  3. An authenticate method that returns the user when the password is correct (and false otherwise)
22
Q

How do you run migrations for production in Heroku?

A

heroku run rails db:migrate

23
Q

If you view your app running in production, it won’t work without a production database, how do you create a database in production?

A

rails db:migrate RAILS_ENV=production

24
Q

What do strong parameters do?

A

allows us to specify which parameters are required and which ones are permitted. This prevents unwanted mass assignment.

25
Q

What is mass assignment?

A

Mass assignment allows us to set a bunch of attributes at once instead of one at a time. We can set a user’s username, password, and avatar all at once instead of setting each one one at a time.

26
Q

What does the method any? do

A

Returns true if there are any elements present and false otherwise.

27
Q

How are error messages generated?

A

They are generated based on the validations you add to your model.

28
Q

What is another way to write redirect_to @user

A

redirect_to user_url(@user)

29
Q

How do you enable SSL for the application

A

uncomment#config.force_ssl = true in production.rb, the configuration file for production applications.

30
Q

Why use sessions?

A

HTTP is a stateless protocol, treating each request as an independent transaction that is unable to use information from any previous requests. This means there is no way within the hypertext transfer protocol to remember a user’s identity from page to page; instead, web applications requiring user login must use a session, which is a semi-permanent connection between two computers (such as a client computer running a web browser and a server running Rails).

31
Q

What are cookies?

A

small pieces of text placed on the user’s browser. Because cookies persist from one page to the next, they can store information (such as a user id) that can be used by the application to retrieve the logged-in user from the database.

32
Q

When would you use the method flash.now

A

re-rendering a template with render doesn’t count as a request. if we submit invalid login information and then click on the Home page, the flash gets displayed a second time.

flash.now is specifically designed for displaying flash messages on rendered pages. Unlike the contents of flash, the contents of flash.now disappear as soon as there is an additional request,

33
Q
Explain does this code:
module SessionsHelper
  def log_in(user)
    session[:user_id] = user.id
  end
end
A

This places a temporary cookie on the user’s browser containing an encrypted version of the user’s id, which allows us to retrieve the id on subsequent pages using session[:user_id]. In contrast to the persistent cookie created by the cookies method, the temporary cookie created by the session method expires immediately when the browser is closed. Because temporary cookies created using the session method are automatically encrypted, the code is secure, and there is no way for an attacker to use the session information to log in as the user. This applies only to temporary sessions initiated with the session method, though, and is not the case for persistent sessions created using the cookies method.

34
Q

Explain the difference between _path vs. _url helper methods

A

The users_url helper generates a URL that includes the protocol and host
name. The users_path helper generates only the path portion.

users_url: http://localhost/users
users_path: /users

Mostly you should use the _path flavor. If you need to spec the host or
protocol (like for talking to another app or service), then use the _url
flavor.

35
Q

Why would I write the following like this:
def current_user
User.find_by(id: session[:user_id])
end

and not like this:
def current_user
User.find(id: session[:user_id])
end

A

Because #find raises an exception if the user id doesn’t exist. This behavior is appropriate on the user profile page because it will only happen if the id is invalid, but in the present case session[:user_id] will often be nil (i.e., for non-logged-in users).Rather than raising an exception, this method returns nil (indicating no such user) if the id is invalid.

36
Q

For a method login:
def log_in(user)
session[:user_id] = user.id
end

How would you destroy a user session, doing the reverse of login?

A
def log_out
    session.delete(:user_id)
    @current_user = nil
  end
37
Q

What is a packet sniffer and how can you protect your application against it?

A

A packet sniffer is a computer program or piece of computer hardware that can intercept and log traffic that passes over a digital network or part of a network.

Use SSL which encrypts your data

38
Q

What 2 values does the cookie method take?

How would you code a cookie for a remember token that is set to expire in 10 years?

A

A cookie consists of two pieces of information, a value and an optional expires date.
cookies[:remember_token] = { value: remember_token,
expires: 10.years.from_now.utc }

39
Q

Permanent cookies are commonly set to expire in 20 years. What is the common short-hand to writing this?

A

cookies.permanent[:remember_token] = remember_token

40
Q

What method is used to securely encrypt a cookie?

A

cookies#signed

cookies.permanent.signed[:user_id] = user.id

41
Q

Explain how Rails ‘fakes’ a PATCH request in a form

A

Since web browsers can’t natively send PATCH requests, Rails fakes it with a POST request and a hidden input field

42
Q

How does Rails know to use a POST request for new users and a PATCH for editing users?

A

When constructing a form using form_for(@user), Rails uses POST if @user.new_record? is true and PATCH if it is false.

43
Q

Your model uses the method has_secure_password. What would you add to a password validation to allow a user to update their username or other attributes without providing a password?

A

allow_nil: true

In case you’re worried that allow_nil: true might allow new users to sign up with empty passwords, recall from that has_secure_password includes a separate presence validation that specifically catches nil passwords. Because nil passwords now bypass the main presence validation but are still caught by has_secure_password

44
Q

Why would you not include the attribute :admin in your strong params?

A

Don’t include attributes you don’t want to be editable. If we simply passed an initialization hash in from an arbitrary web request, a malicious user could send a PATCH request. admin is not in the list of permitted attributes. This is what prevents arbitrary users from granting themselves administrative access to our application.