arailsdemo 6

添加一个 导航条(Navigation Bar)

app/views/shared/_nav_bar.html.haml

#navBar
  %ol
    %li= link_to 'Home', root_url
    %li= link_to 'Building This Site', posts_url
    %li= link_to 'Sections', sections_url
    %li= link_to 'Snippets', snippets_url

修改 Application Layout (布局)

app/views/layouts/application.html.haml

%html(lang="en")
%html(lang="en")
  %head
    ...
  %body.two-col.bp
    #container
      #header
        #logo aRailsDemo
      .clear

      = render 'shared/nav_bar'
      #content
        #innerContent
          - flash.each do |name, msg|
            = content_tag :div, msg, :id => "#{name}"

          - if yield(:title)
            %h1= yield(:title)

          = yield

      #sidebar
        #innerSidebar
          Future Content

改进的 Post Navigation(导航)-修改 Post Controller

app/controllers/post_controller.rb

class PostsController < ApplicationController
  ...
  def show
    @post = Post.find_by_sequence(params[:id])
  end

  def edit
    @post = Post.find_by_sequence(params[:id])
    ...
  end

  def create
    @post = Post.new(params[:post])
    if @post.save
      redirect_to( post_url(@post.sequence), :notice => 'Post was successfully created.')
    else
      ...
    end
  end

  def update
    @post = Post.find(params[:id])
    if @post.update_attributes(params[:post])
      redirect_to(post_url(@post.sequence), :notice => 'Post was successfully updated.')
    else
      ...
    end
  end

  def destroy
    @post = Post.find_by_sequence(params[:id])
    ...
  end
end

同上,改进的 Post Navigation(导航)-修改Post Index 页面

app/views/posts/index.html.haml

- title "Building This Site"

- @posts.each do |post|
  .postShow
    ...
    .title= link_to post.title, post_url(post.sequence)
    ...
    .admin
      = link_to 'Edit', edit_post_path(post.sequence)
      = link_to 'Destroy', post_url(post.sequence), :confirm => 'Are you sure?', :method => :delete
    ...

model 里实现给定一个 post, 能够找到其 preview 和 next

app/models/post.rb

class Post < ActiveRecord::Base
  ...
  def post(position)
    increment = position == :previous ? -1 : 1
    Post.find_by_sequence(self.sequence + increment)
  end
end

在视图里实现以上所说的方法,我们需要 辅助方法:

app/helpers/post_helpers.rb

module PostsHelper
  def post_link(position)
    link_to("#{position.to_s.capitalize} Post", post_url(@post.post(position).sequence)) if @post.post(position)
  end
end

在Post Show 页面的具体使用

app/views/posts/show.html.haml

- title "\##{@post.sequence} #{@post.title}"
...

-# edited 12/19/10
.postNav
  .prev= post_link(:previous)
  .next= post_link(:next)
%br
%br
%p= link_to 'View All Posts', posts_path
...

你可能感兴趣的:(arailsdemo 6)