Week 1 Questions Flashcards
what does update_attributes do?
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 would you find a user or any other model by specific attributes like and email or username?
User.find_by(email: “mhartl@example.com”)
how do you develop in the rails console without making any changes to the application?
rails console –sandbox
what do migrations do?
Migrations provide a way to alter the structure of the database incrementally, so that our data model can adapt to changing requirements.
how do you write a named route?
#original route name: get 'static_pages/help'
#named route name get '/help', to: 'static_pages#help'
what are the 3 types of assets and how are they used?
- 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
why use instance variables?
they are automatically available in the views and they can be used throughout a class
what is a difference between single quotes and double quotes?
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 do you save changes on a branch and then merge them with the master?
$ git add -A $ git commit -m "Finish static pages" $ git checkout master $ git merge static-pages $ git push
explain this ruby idiom: a||=b
a =b when a == false
otherwise a remains unchanged
What is a Module? Can you tell me the difference between classes and modules?
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
String vs Symbol
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.
What is a callback?
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.
Should a callback be public?
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.
What is the difference between private and protected?
- 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 do you display all errors for a user model?
user.errors.full_messages
What should be the maximum length for an email attribute and why?
Maximum length of strings for many databases is 255
How do you enforce uniqueness at the model level?
class User < ApplicationRecord validates :name, uniqueness: true end
How do you enforce uniqueness at the database level?
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
Why would you add an index to an email address attribute?
it prevents a full-table scan when finding users by email address
What 3 points of functionality does the method has_secure_password have when added to a model?
- The ability to save a securely hashed password_digest attribute to the database
- A pair of virtual attributes (password and password_confirmation), including presence validations upon object creation and a validation requiring that they match
- An authenticate method that returns the user when the password is correct (and false otherwise)
How do you run migrations for production in Heroku?
heroku run rails db:migrate
If you view your app running in production, it won’t work without a production database, how do you create a database in production?
rails db:migrate RAILS_ENV=production
What do strong parameters do?
allows us to specify which parameters are required and which ones are permitted. This prevents unwanted mass assignment.
What is mass assignment?
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.
What does the method any? do
Returns true if there are any elements present and false otherwise.
How are error messages generated?
They are generated based on the validations you add to your model.
What is another way to write redirect_to @user
redirect_to user_url(@user)
How do you enable SSL for the application
uncomment#config.force_ssl = true in production.rb, the configuration file for production applications.
Why use sessions?
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).
What are cookies?
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.
When would you use the method flash.now
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,
Explain does this code: module SessionsHelper def log_in(user) session[:user_id] = user.id end end
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.
Explain the difference between _path vs. _url helper methods
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.
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
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.
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?
def log_out session.delete(:user_id) @current_user = nil end
What is a packet sniffer and how can you protect your application against it?
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
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 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 }
Permanent cookies are commonly set to expire in 20 years. What is the common short-hand to writing this?
cookies.permanent[:remember_token] = remember_token
What method is used to securely encrypt a cookie?
cookies#signed
cookies.permanent.signed[:user_id] = user.id
Explain how Rails ‘fakes’ a PATCH request in a form
Since web browsers can’t natively send PATCH requests, Rails fakes it with a POST request and a hidden input field
How does Rails know to use a POST request for new users and a PATCH for editing users?
When constructing a form using form_for(@user), Rails uses POST if @user.new_record? is true and PATCH if it is false.
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?
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
Why would you not include the attribute :admin in your strong params?
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.