Real World Example: Honey-Do Task List

Just to get our feet wet in the Rails/Ajax world, let’s create a simple application that will manage our honey-do tasks. What we want to achieve is to be able to dynamically add and remove tasks, all using Scriptaculous and Prototype. Let’s get started.

  1. Create a new Rails application called “honey-do”:

    rails honey-do
  2. Now let’s create the Task model with some fields:

    ./script/generate model Task name:string priority:integer 
      completed:boolean

    Run the rake command to generate the database, then the command to run the migrations:

    rake db:create   # This is necessary only if the db isn't 
                     # created and you are not using SQLite3
    rake db:migrate
  3. Create the Tasks controller:

    ./script/generate controller tasks
  4. Now that we have the infrastructure in place, let’s start adding some code. First, let’s add some methods to the Task model and give it a validator:

    # app/models/task.rb
    
    class Task < ActiveRecord::Base
      
      validates_length_of :name, :minimum => 3, 
                          :message => 
                           "must be at least 3 characters long"
      
      # This is our list of available priorities.
      def self.priorities
        %w(1 2 3 4 5)
      end
      
      # Helper method to get open tasks sorted by priority
      def self.open_tasks
        Task.find(:all, :order => [:priority], :conditions =>  
         ["completed = ?", false])
      end
      
    end

    Note that our Task model requires that the length of the name is at least three characters. We also created two static helper methods.

  5. Now let’s take a look at the controller:

    # app/controllers/tasks_controller.rb class TasksController ...

Get Rails Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.