Learning Ruby

Reference, Mnemonic & Ramblings

Quiz for Rails Beginners 2

Here's the second quiz for people who are just getting started learning web-application development. This focuses more on the resources routes and related concepts in Rails.

Each question is a link pointing to my corresponding answer as i understand the concepts the today.

  1. Name all the 7 (or 8) routes exposed by the resources keyword in the routes.rb file. Also name the 4 named routes, and how the request is routed to the controller/action.

  2. What is REST and how does it relate to the resources routes?

  3. What's the major difference between model backed and non-model backed form helpers?

  4. How does form_for know how to build the <form> element?

  5. What's the general pattern we use in the actions that handle submission of model-backed forms (ie, the create and update actions)?

  6. How exactly do Rails validations get triggered? Where are the errors saved? How do we show the validation messages on the user interface?

  7. What are Rails helpers?

  8. What are Rails partials?

  9. When do we use partials vs helpers?

  10. When do we use non-model backed forms?

MY ANSWERS:

A1: Having resources :dogs in the block in the routes.rb file is going to give us the following routes

Prefix Verb URI Pattern Controller#Action
dogs GET /dogs(.:format) dogs#index
POST /dogs(.:format) dogs#create
new_dog GET /dogs/new(.:format) dogs#new
edit_dog GET /dogs/:id/edit(.:format) dogs#edit
dog GET /dogs/:id(.:format) dogs#show
PATCH /dogs/:id(.:format) dogs#update
PUT /dogs/:id(.:format) dogs#update
DELETE /dogs/:id(.:format) dogs#destroy

Back

A2: REST (REpresentational State Transfer) is a way to maintain data persistence in stateless data-transfer protocol (which is HTTP in our case). The resources keyword in the routes.rb file creates the most used 7 routes (listed above) in a Rails application. These routes are RESTful because they conform to the REST architectural constraints for web application development. Back

A3: The major difference is a model-backed helper requires, and directly works on, a ActiveRecord Model object for creation of equivalent HTML tags. This makes it very tightly integrated with the model object and it's attributes. A non-model backed helper is a more generic helper to create HTML tags and does not need any ActiveRecord Model object to work on.
Back

A4: Because the form_for is a model-backed form helper, it takes an ActiveRecord Model object to create an HTML form for using the model object's real and virtual attributes.
Back

A5: The general pattern we use in actions that handle model-backed form submission is:
  1. Create/Update Model Object in Memory
  2. Try to save it in the database
  3. If the save succeeds, redirect to the relevant page (showing the saved item by itself or in a list)
  4. If the save fails, render the page that submitted the form again, with the error messages (stored on the in-memory object) displayed
The equivalent code for the create action of the Category controller would look like this:
1
2
3
4
5
6
7
8
9
10
def create
  @category = Category.new(params.require(:category).permit(:name))

  if @category.save
    flash[:notice] = 'New category created.'
    redirect_to categories_path
  else
    render :new
  end
end
Slightly different from the create action, the update action would like like this:
1
2
3
4
5
6
7
8
9
10
def update
  @category = Category.find(params[:id])

  if @category.update(params.require(:category).permit(:name))
    flash[:notice] = 'Category updated.'
    redirect_to category_path(@category)
  else
    render :edit
  end
end
Back

A6:
  • Model validations are triggered when the database is accessed for update, for example: the save or create methods are called on a model object
  • If there are validation errors triggered during the above operation, they are saved on the model object itself which can be accessed by calling #errors on it
  • Note: model_obj.errors.full_messages can be used to retrieve an array of error messages
  • This object cab be saved in an instance variable of the controller class and then can be used in the rendered template to display errors as shown below
1
2
3
4
5
6
7
8
9
10
11
12
<% if model_obj.errors.any? %>
  <div class='row'>
    <div class='alert alert-error span8'>
      <h5>Please fix the errors below to submit successfully:</h5>
      <ol>
        <% model_obj.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ol>
    </div>
  </div>
<% end %>
Back

A7: Rails helpers are methods that can be defined to contain repetitive logic for the presentation layer (used by the view templates). These helper methods usually go in the app\helpers\application_helper.rb file under the Rails project folder.
Back

A8: Rails partials are HTML snippets which need to be reused in many view templates with no or minimum modifications (that can be handled by arguments). Filenames for partials begin with an _, for example: _errors.html.erb. This partial can be used by calling the render method on it, as in <%= render 'shared/errors', model_obj: @post %> where model_obj is an argument variable name that will be used in the partial (refer to the HTML code in Answer 6 above).
Back

A9: Partials should be preferred over helpers when too much HTML needs to be embedded. Helpers should be reserved more for the logic (parsing / reformating / calculations) than the presentation itself. Back

A10: Non-model backed form helpers should be used whenever user-input elements need to be generated for properties which are not the associated attributes of an ActiveRecord Model object.
Back

comments powered by Disqus