Misc Flashcards
What are the 7 routes created for CRUD operations on a resource and their respective action methods?
For example, for a resource called photos:
HTTP Verb, Path, Action
GET, /photos, index
GET, /photos/new, new
POST, /photos, create
GET, /photos/:id, show
GET, /photos/:id/edit, edit
PATCH/PUT, /photos/:id, update
DELETE, /photos/:id, destroy
What is the difference between POST, PUT and PATCH?
REST denotes that:
A request using the POST method should act upon the resource collection; adding a new resource to the collection Example URL: http://example.com/resources
A request using the PUT HTTP verb should act upon a single resource within the collection; replacing the resource wholly upon the server Example URL: http://example.com/resource/1
A request using the PATCH HTTP verb should act upon a single resource within the collection; updating certain attributes upon the resource where it stands Example URL: http://example.com/resource/1 (PATCH is used for partial updates.)
How can you define a route to be used with multiple HTTP methods?
With match and via: list of http verbs
Eg.
match ‘products/:id’ => ‘products#show’, via: [:get, :post]
What route helpers are created for the following route?
get ‘help’ => ‘help#index’, as: ‘help’
help_path (“/help”) and help_uri (“http://www.example.com/help”)
What are the 7 named paths created for CRUD operations on a resource?
photos_pathreturns/photos
new_photo_pathreturns/photos/new
edit_photo_path(:id)returns/photos/:id/edit(for instance,edit_photo_path(10)returns/photos/10/edit)
photo_path(:id)returns/photos/:id(for instance,photo_path(10)returns/photos/10)
In what order are parent and child classes action callbacks called?
-
How do you skip an action callback?
Eg
Before action :
skip_before_action :action_name
Around action
skip_action_callback :action_name
How can you prevent sql injection attacks?
Avoid string concatenation to create your query, and use question marks to pass parameters which will sanitize your query.
For example:
@persons = People.where(“persons.name LIKE concat(‘%’, ?, ‘%’)”, params[:search])
How do you specify a read-only attribute?
Using attr_readonly method on your model.
What is the difference between calling delete or destroy on an object?
Destroy loads the instance of the ActiveRecord object and triggers before_destroy callbacks or deletes dependent associations child objects. Delete does not, which means it’s also faster.
What are 3 ways in which you can write a query to find users by their city and age?
-
How do optimistic and pessimistic locking behave in rails?
Optimistic locking doesn’t operate on the database level (doesn’t actually lock the tables or rows in the database) but if two users edit the same data, when the second tries to save it throws a StaleObjectError (even when save () is used which doesn’t throw an exception on validation errors.
Pessimistic locking operates at the database level and locks the rows until a first transaction is finished, before it allows other users to read the data.
What is the default ordering if no ‘order by’ clause is specified in a query?
None actually. This seems to trip people since the common belief is that ‘order by id asc’ is the default
How do you get a random record?
An example could be using a random offset
Eg.
User.offset(rand(User.count)).limit(1)
It’s important to make sure you don’t load all the data from the table for one row
What ruby gems do you like/have you used??
Some examples:
Httparty
Aws sdk rails
Activerecord-import - bulk import
Rubocop, byebug
State_machine & aasm
Rspec, fabricator / factory girl
Devise
Resque, Sidekiq
Paperclip, carrierwave
What are some disadvantages for using Rails?
Fat models; concerns can take some of the load off.
What backend queuing systems do you know/have you used?
Some examples: DelayedJob, Resque, Sidekiq, AWS SQS (although with this last one the messages can be processed more than once so it shouldn’t be used for email sending)
What callbacks do you know?
Some examples: before_validation, after_validation, before_create, after_create, before_save, around_save, (which uses yield).
What are middlewares used for?
Dispatching requests, session handling, parsing params, whitelisting domains
What are strong parameters?
Rails provides an interface to specify whitelisted attributes and doesn’t allow mass assignment of parameters from action controllers.
For example, how o specify whitelisted attributes:
params.require(:person).permit(:name, :age)
What are keyword arguments?
Arguments specified by symbols.
def obvious_total(subtotal:, tax:, discount:)
subtotal + tax - discount
end
obvious_total(subtotal: 100, tax: 10, discount: 5) # => 105
- order of parameters doesn’t matter
- method call is more readable
vs
def mysterious_total(subtotal, tax, discount)
subtotal + tax - discount
end
mysterious_total(100, 10, 5) # => 105
How do you solve N+1 query problems?
includes delegates the job to #preload or #eager_load depending on the presence or absence of condition related to one of the preloaded table.
Using eager loading. There are 3 methods that can be uased to achieve this: #includes, #preload or #eager_load.
What is the difference between the following two?
scope :from_the_past, where(“happens_at <= ?”, Time.now)
scope :from_the_past, -> { where(“happens_at <= ?”, Time.now) }
In the first scenario, Time.now will always be the time when the class was loaded. Using lambdas (second example), the code is lazy loaded, which means it evaluates when called.
Rails supports put and patch. Major browsers don’t support these http methods. How does rails deal with this?
It actually does a POST under the hood. Forms include a hidden field keeping track of this.