Getting Started with a Simple Application

To get our feet wet, let's start with a simple introductory example. I am going to call the application “Thought Log.” Thought Log will simply take what is entered in a text field and log it into the current page without reloading. First, create the new Rails project.

cody> rails thought_log

Now, let's generate a new controller, ThoughtsController, that will hold our actions.

cody> ruby script/generate controller Thoughts
          exists  app/controllers/
          exists  app/helpers/
          create  app/views/thoughts
          create  test/functional/
          create  app/controllers/thoughts_controller.rb
          create  test/functional/thoughts_controller_test.rb
          create  app/helpers/thoughts_helper.rb

The generator has created the controller, helper, and a folder for the controller's views. Now we'll add two actions. The first action, index(), displays the initial empty list of thoughts. The second action, log(), is called in the background using Ajax and the response adds the new thought to the already rendered index page.

class ThoughtsController < ApplicationController
  def index
  end

  def log
    @thought = params[:thought]
  end
end

The log() action simply assigns the value of params[:thought] to the instance variable @thought and then renders the view template app/views/thoughts/log.rjs. We are following the Rails convention that the controller by default renders a view template with the same name as the action that is executing. Since .rjs templates are just another template, Rails looks in the controller's ...

Get RJS Templates for Rails 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.