Ruby on Rails (3)

1. Migration

After add in the /db/migrate/002_XX_.rb

def self.up
create_table :votes do |t|
t.column :story_id, :integer
t.column :created_at, :datetime

run the command: $rake  db:migrate

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

class Vote < ActiveRecord::Base
belongs_to :story

there’s no need to store association information in both models when defining a one-to-many relationship. The information is always stored on the “many” side of the relationship.

2. Route URLs  (which is not work after run code, we do not need to add stuff in route.rb)

clean urls: /story/show/1

By default, the Routing module operates as follows:
The first part of the URL is mapped to the corresponding controller. In this
example, /story would route to our StoryController controller.
The second part of the URL routes to the action name. In this case, the show
action would be invoked.
The third part is used to populate the id entry in the params hash. In our
example, the value of params[:id] would be set to 1.

Inorder to change the url to: /story/show/my-shiny-weblog,

we need to modify /config/routes.rb


map.story ‘story/show/:permalink’,
:controller => ‘story’,
:action => ‘show’

“:permalink” will be placed in the params[:permalink] hash area

The original two calls to map.connect are Rails routes—rules that specify how a URL
should be mapped. Routes are read from top to bottom; the route with the lowest
priority is the one at the very bottom of the list.

we use map.story, because it is a named route.

A named route is a custom alias for matching an incoming request’s URL.

3. Add a new value (permalink) to Story model, without build a new model.

To add a migration without adding a new model, we use the generate script,
passing migration as the first parameter:
$ ruby script/generate migration AddPermalinkToStories

class AddPermalinkToStories < ActiveRecord::Migration
def self.up
add_column :stories, :permalink, :string
def self.down
remove_column :stories, :permalink

Then apply this migration: $ rake db:migrate

From the Rails console, fetch a single Story. Update its permalink attribute using
the update_attribute method:

s.update_attribute :permalink, ‘my-shiny-weblog’

So when the route is like that, we can define show method:

def show
@story = Story.find_by_permalink(params[:id])

it did not work if you write id to permalink.

4. Links

<%= link_to,
story_url(:permalink => @story.permalink) %>

if we want use story_url, we need modify route.rb as 2 described.

a story_url function exists for our use is a direct result of the
map.story call in the route configuration.

The story_url function accepts a hash of values that’s used dynamically to generate the URL we’re looking for. In this case, our named route takes only a single parameter—the permalink. The value of the permalink of the randomly picked Story is passed using the
:permalink symbol.

5. Ajax (Asynchronous JavaScript and XML,)

Ajax is a technique for communicating between client and server.

Ajax enables a web browser to continue to communicate with a web
server without reloading the entirety of the page it’s showing—a technique that’s
also known as remote scripting.

As both of the helpers that we’re going to use—Prototype, for dealing with the
XmlHttpRequest object, and, for displaying visual effects—are
implemented in JavaScript, we need to include the appropriate JavaScript files
into our application’s layout. To do so, add the following line to the
app/views/layouts/application.rhtml file, somewhere in the head section:

<%= javascript_include_tag :defaults %>

This line calls the javascript_include_tag Rails helper, passing it the :default
parameter. It causes a total of five JavaScript include files to be added to our
prototype.js This file contains the entire Prototype library, which provides
our Ajax functionality.
effects.js This is the visual effects part of the library.
dragdrop.js This file contains the JavaScript methods required for adding
drag-and-drop functionality, also from the
controls.js The auto-completion methods are contained within this part
of the library.
application.js This is an empty file that we can use to store our own custom
JavaScript functions. It’s located in the public/javascripts
folder of our application.


<span id=”vote_score”>
Score: <%= @story.votes.count %>
<%= %>
<%= link_to, %>
<div id=”vote_link”>
<%= link_to_remote ‘shove it’,
:url => { :action => ‘vote’, :id => @story } %>

we need add vote in controller:

def vote
@story = Story.find(params[:id])

6. RJS

under app/views/story/

templates with an .rjs extension (short for Rails JavaScript) are used to modify parts of an existing page. When we use RJS templates, the information that’s transferred to the user’s browser is a series of JavaScript instructions that modify, extend, and apply visual effects to HTML elements. In contrast, .rhtml templates transfer HTML elements themselves.

page.replace_html ‘vote_score’, Score: #{@story.votes.count}”
page[:vote_score].visual_effect :highlight

#{} syntax: add dynamic values to our strings.

7. To support both Ajax and without Ajax:

<div id=”vote_link”>
<%= link_to_remote ‘shove it’,
{ :url => { :action => ‘vote’, :id => @story } },
{ :href => url_for(:action => ‘vote’, :id => @story) } %>

def vote
@story = Story.find(params[:id])
respond_to do |wants|
wants.html { redirect_to :action => ‘show’,
:permalink => @story.permalink }
wants.js { render }

8. Vote history:

Implement the voting history as a list, using the HTML elements for an unordered list (ul). Each vote will be represented as a list item (li) that shows the voting timestamp.

The list items themselves will be rendered as partials, so a single template that contains a single list item will be rendered as often as there are votes for a given story.

<ul id=”vote_history”>
<% if %>
<em>No shoves yet!</em>
<% else %>
<%= render :partial => ‘vote’,
:collection => @story.votes %>
<% end %>

A partial is identified by an underscore (_) prefix in its filename.

create a new partial at app/views/story/_vote.rhtml

<li><%= vote.created_at.to_formatted_s(:short) %></li>

to_formatted_s, is available as an instance method for objects of the classes Date and Time

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s