arailsdemo 8

简单的管理 (Administration)

创建一个 Sessions Controller

app/controllers/sessions_controller.rb

class SessionsController < ApplicationController  
  def new  
  end  

  def create
    session[:name] = params[:name]
    session[:pw] = params[:password] 
    if admin?
      redirect_to root_url, :notice => "Successfully logged in"
    else
      render 'new'
    end
  end  

  def destroy  
    reset_session  
    flash[:notice] = "Logged out" 
    redirect_to root_url 
  end  
end

给 Controller 也来一点 Helper Methods

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  helper_method :admin?

  protect_from_forgery

  protected

  def admin?
    session[:name] == "login" && session[:pw] == "password"
  end

  def authorize
    unless admin?
      redirect_to root_url
      # false   # edited 11/17/10 -- not needed
    end
  end
end

让 posts controller 安全一点

app/controllers/posts_controller.rb

class PostsController < ApplicationController
  before_filter :authorize, :except => [:index, :show]
  ...
end

添加 Sessions 到路由( Routes )

config/routes.rb

Mysite::Application.routes.draw do

  post 'login', :to => 'sessions#create'
  match 'login', :to => 'sessions#new', :as => 'login'
  match 'logout', :to => 'sessions#destroy', :as => 'logout'
  ...
end

添加一个登录页面(Login View)

app/views/sessions/new.html.haml

= form_tag login_path do
  Name:
  = password_field_tag :name
  %br
  Password:
  = password_field_tag :password
  %br
  = submit_tag "Login"

将 '登录' 放到导航条里

app/views/shared/_nav_bar.html.haml

#navBar
  %ol
    ...
    - if admin?
      %li= link_to 'Sections', sections_url
      %li= link_to 'Snippets', snippets_url
      %li= link_to 'Logout', logout_url
    - else
      %li= link_to 'Login', login_url

更改 Post 视图页面(index 和 show)

app/views/posts/index.html.haml and show.html.haml

-# index.html.haml

- title "Building This Site"

- if admin?
  = link_to 'New Post', new_post_path    # 1/9/11 - moved this from bottom of page

- @posts.each do |post|
  .postShow
    ...    
    - if admin?
      .admin
        = link_to 'Edit', edit_post_path(post.sequence)  # 1/9/11 fixed typo
        = link_to 'Destroy', post_url(post.sequence), :confirm => 'Are you sure?', :method => :delete   # 1/9/11 fixed typo
    .clear
_______________________________

-# show.html.haml
...
-if admin?
  = link_to 'Edit', edit_post_path(@post.sequence)
  |
  = link_to 'New', new_post_path

对权限方面的过滤器做一些更改

app/controllers/application_controller.rb, posts_controller.rb

# application_controller.rb
class ApplicationController < ActionController::Base 
  before_filter :authorize
__________________________________________________

# sessions_controller.rb
class SessionsController < ApplicationController
  skip_filter :authorize

__________________________________________________
# posts_controller.rb
class PostsController < ApplicationController
  before_filter :authorize, :except => [:index, :show]

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