Ruby on Rails (2)

1. Helper:

A helper is a chunk of code that can be reused throughout an application, and is stored in a helper file.

A new helper file called controllername_helper.rb.

Helpers associated with a particular controller are available only to the views of
that particular controller. However, there is one “special” group of helpers—those
defined in the file app/helpers/application_helper.rb. These helpers are
called global helpers and become available to any view throughout your application.

2. form page:

<% form_for :story do |f| %>
The form_for helper creates a form that’s bound to a specific
object—in this case, it’s bound to the @story instance variable, as indicated by
the inclusion of the :story symbol at the beginning of the block.


class StoryController < ApplicationController

def index
@story = Story.find(:first, :order => ‘RAND()’)
def new
@story =[:story])

if                                           #http的头 是 post
redirect_to :action => ‘index’

#params: hash table, contains all of the content that the user submitted (the value of the name attribute could be accessed as params[:story][:name])

def 的method: index, new 对应 each website: eg: XXX/new


4. layout:

A layout template can basically be given any name, as long as the file ends in .rhtml. If the filename is application.rhtml, Rails will adopt this as the default layout.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN””&gt;
<html xmlns=”;
xml:lang=”en” lang=”en”>
<meta http-equiv=”Content-type”
content=”text/html; charset=utf-8″ />
<%= stylesheet_link_tag ‘style’ %>  #add style.css file in /public/stylesheet
<div id=”content”>
<%= yield %>  #point at which the content for our specific view is displayed.

we ensure that the <link> element that’s generated will point to the URL /stylesheets/style.css.

layout files is in /app/views/layouts

5. flash

“Flash” also happens to be the name for the internal storage container (actually a kind of hash) that Rails uses for temporary data. Use the flash to pass temporary objects between actions.  Items stored in the flash exist for the duration of exactly one action, and then they’re gone.

Using the flash allows us to conveniently communicate information between successive actions without having to save information in the user’s browser or the database. The flash is well positioned to store short status messages, such as notifications that inform the user whether or not a form submission or login attempt was successful.

flash[:error] = ‘Login unsuccessful.’

The common area names are :notice, :warning, and :error.

To retrieve contents from the flash (usually done in the successive action), just
access the flash from a view in the same way that you would access any other
hash in Rails.

<% unless flash[:notice].blank? %>
<div id=”notification”><%= flash[:notice] %></div>
<% end %>

6. Validation

Validations are defined in the model. This ensures that the validation is always
applied, and, therefore, that an object is always valid, before its data is saved to
the database. ( app/models/story.rb)

class Story < ActiveRecord::Base
validates_presence_of :name, :link

in story_controller.rb:

def new
@story =[:story])
if and        #check validation first, then print notice
flash[:notice] = ‘Story submission succeeded’
redirect_to :action => ‘index’

<%= error_messages_for ‘story’ %>  #add to new.rhtml


7. TestModel:

test/unit/story_test.rb  test model

def test_should_require_name
 s = Story.create(:name => nil)   # creat a instance of story, the name is nil
   assert s.errors.on(:name)            # error exist in s name field

Every model object in Rails has an errors attribute. This attribute contains the
results of any validations that have been applied to it—if the validation failed,
errors will exist “on” that attribute.

def test_should_create_user
s = Story.create(
:name => ‘My test submission’,
:link => ‘;)
assert s.valid?    #this method returns true if no validation errors are present.


Run the test cases: $ rake test:units

YML file should use Blank not Tab


8. Test Controller:


def test_should_show_index
get :index          # simulate http GET
assert_response :success   # checks that the HTTP response code we receive
assert_template ‘index’   # the request we made is actually rendered with the template

that we expect

assert_not_nil assigns(:story)

Other mappings that can be used with the assert_response function include
:redirect for HTTP redirect headers and :missing for the all-too-common
“404 Not Found” error that occurs when a request is made for a file that
doesn’t exist.


assert_select ‘form p’, :count => 3 :

checks for the existence of one form element in which five p elements are nested (the count
is supplied using the :count argument).

assert_select: a certain HTML element is present in the document
that’s returned from a request. assert_select can even verify the hierarchy of the HTML element, regardless of how deeply it is nested; it can also test the element’s attributes (for example, the value of its class or id).

Run these test case together: $ rake test

This entry was posted in Website design and implement. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s