蓝天,小湖,湖水中一方小筑

RoR learning log (2)

This article will finish the ToDo web application, and the prime area in this article is adding validator and updating templates.

Here is to RoR learning log (1)

According to the requirements, the length of ToDo account should less than 100 characters and the status of ToDo can only be chosen from 0 or 1, so some validator should be added to the model. With the validator, the model code should be looked like:

STATUS_OPTION = [0, 1]

class ToDo < ActiveRecord::Base
  attr_accessible :content, :status
  validates :content, :presence => true,
                      :length => { maximum: 100 }
  validates :status, :presence => true,
                     :numericality => { :only_integer => true },
                     :inclusion => { :in => STATUS_OPTION }
end

Statements started with validates keyword are validator. The available condition list can be checked at this page. If the value passed in break the rule, the error message will be shown in the page.

With the validators, the value saved can be guaranteed to be correct. But seems radio box or drop down box is better than the text field, so we plan to modify the template page. The template is placed under app/views/to_dos directory, which is a HTML file with some template control commands. By default, when viewing the URL http://[address]/index, the template with the same name, index.html.erb, will be rendered. The generated form is saved in file _form.html.erb, the default type of status is number_field, which should be updated to select. The document for select is [here](http://api. rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#M001593), according the document, the option list should be provided, and here we can use the constant STATUS_OPTION defined in model file. Here is the updated status field in the form object:

  <%= f.label :status %>  

  <%= f.select :status, ToDo::STATUS_OPTION %>

The form type will change from text field to drop down menu after updating the form.

Congratulations, a simple ToDo application has been worked out. It is a very simple application, which do not contain the static files, user authentication, unit test and so on. In next step, I plan to re-write the linuxfb website with more better structure, hope can touch more features in RoR.