Component Scripting Examples

Model statements

These are examples for validating model properties:

  validates :title, :presence => true

  validates :rating, :numericality => true, :within => 1..10

See pp. 105 - 110 for additional examples.

Controller

These statements get content from a database table:

   # retrieve a list
   @items = Item.all

   @item = Item.first

   @items = Item.find_all_by_name("Sam")

   @items = Item.order("rating DESC")

All of the above statements use ActiveRecord, which is summarized in chapter 4.



Views

Here's a form that demonstrates helpers to create a variety of form inputs:

<% form_for(@review) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :clarity %><br />
    Poor <%= f.radio_button :clarity, "1" %>
    
    Good <%= f.radio_button :clarity, "2" %>
    Excellent <%= f.radio_button :clarity, "3" %>
  </p>

  <p>
    <%= f.label :soundness %><br />
    <%= f.select :clarity, [['Unsatisfactory', 1],
                               ['Marginal', 2],
                               ['Satisfactory, 3],
                               ['Good, 4],
                               ['Excellent, 5]]     %>
    
  </p>


  <p>
  <%= f.check_box :late %> Late
  </p>

<% end %>

The guide on Rails Form Helpers provides good examples on creating forms and controls. Note that forms come in two flavors: Basic Forms and Model-Based Forms. Scaffold generation creates model-based forms. If you are working with a scaffolded form, make sure you are using tags that work with a model-based form.