Ruby on Rails Action Controller学习笔记

自动增加预载model方法:
class StoreController < ApplicationController
 model :cart, :line_item
 observer :stock_control_observer
 # …

如果没有找到相应的action, method_missing()将被调用
如果没有任何action, Rails会直接找template显示.

Ruby on Rails链接
Routing Requests
配置文件:config/routes.rb
ActionController::Routing::Routes.draw do |map|
 map.connect ‘:controller/service.wsdl’, :action => ‘wsdl’
 map.connect ‘:controller/:action/:id’
end

map.connect可用参数:
:defaults => { :name => "value", …}
 设默认值,默认为:defaults => { :action => "index", :id => nil }
:requirements => { :name =>/regexp/, …}
:name => value
:name => /regexp/

实例:
ActionController::Routing::Routes.draw do |map|
 #从上到下优先级降低.
 #’http://my.app/blog/&#39; 直接显示 index
 map.connect "blog/",
   :controller => "blog",
   :action =>"index"
 #按日期访问博客文章列表
 map.connect "blog/:year/:month/:day",
      :controller =>"blog",
      :action =>"show_date",
      :requirements => { :year => /(19|20)dd/,
               :month => /[01]?d/,
               :day => /[0-3]?d/},
      :day =>nil,
      :month =>nil
 # 按文章ID显示文章内容
 map.connect "blog/show/:id",
      :controller => "blog",
      :action =>"show",
      :id => /d+/
 # 管理页面,常规
 map.connect "blog/:controller/:action/:id"
 # 其它
 map.connect "*anything",
      :controller =>"blog",
      :action =>"unknown_request"
 #=> URL>junk
 #=>@params = {:anything=>["junk"], :controller=>"blog", :action=>"unknown_request"}
end

链接生成url_for
@link = url_for :controller => "store", :action => "display", :id => 123
生成:http://pragprog.com/store/display/123
url_for(:controller => "store", :action => "list",
 :id => 123, :extra => "wibble")
生成:http://rubygarden.org/store/list/123?extra=wibble
url_for(:overwrite_params => {:year => "2002"})
生成:http://pragprog.com/blog/2002/4/15
#url_for会使用默认环境中的参数自动补充出完整的地址
#但一般补最后面的
#使用:overwrite_params使之补前面的.
url_for(:year=>year, :month=>sprintf("%02d", month), :day=>sprintf("%02d", day))
用来填充位数???
url_for(:controller => "/store", :action => "purchase", :id => 123)
#=> http://my.app/store/purchase/123
url_for(:controller => "/archive/book", :action => "record", :id => 123)
#=> http://my.app/archive/book/record/123

redirect_to(:action =>’delete’, :id => user.id)
# 和上面的一样:
redirect_to(:action => ‘delete’, :id => user)

default_url_options()
:anchor string #+string
:host string  (helper.pragprog.com:8080)
:only_path boolean
:protocol string ("https://";)
:trailing_slash boolean (+"/"?)

有名字的 Routes
map.date "blog/:year/:month/:day",
    :controller =>"blog",
    :action =>"show_date",
    :requirements => { :year => /(19|20)dd/,
            :month => /[01]?d/,
            :day => /[0-3]?d/},
    :day =>nil,
    :month =>nil
可调用
date_url(:year => 2003, :month => 2)
#=> http://pragprog.com/blog/2003/2

方法
把action藏起来,让它使用URL访问不了.
hide_action :check_credit
def check_credit(order)
# …
end

Controller Environment
request
  domain()
  remote_ip()
  env() 如:request.env['HTTP_ACCEPT_LANGUAGE']
  method (:delete, :get, :head,:post, or :put.)
   delete?, get?, head?, post?, and put?
class BlogController < ApplicationController
 def add_user
  if request.get?
   @user = User.new
  else
   @user = User.new(params[:user])
   @user.created_from_ip = request.env["REMOTE_HOST"]
   if @user.save
    redirect_to_index("User #{@user.name} created")
   end
  end
 end
end

params
cookies
response
session
headers

runder()
更改默认template目录
ActionController::Base.template_root=dir_path
render(:text=>string)
class HappyController < ApplicationController
 def index
  render(:text =>"Hello there!")
 end
end

render(:inline=>string, [ :type =>"rhtml"|"rxml"] )
class SomeController < ApplicationController
 if RAILS_ENV == "development"
  def method_missing(name, *args)
   render(:inline => %{  
    <h2>Unknown action:#{name}</h2>
    Here are the request parameters:<br/>
    <%= debug(params) %> })
  end
 end
end

render(:action =>action_name)
def display_cart
 if @cart.empty?
  render(:action => :index)
 else
  # …
 end
end

render(:file =>path, [ :use_full_path =>true|false] )

render(:template =>name)
class BlogController < ApplicationController
 def index
  render(:template =>"blog/short_list")
 end
end

render(:partial =>name, …)
render(:nothing => true)
render_to_string() 不发送,直接转为string

发送
send_data
def sales_graph
png_data = Sales.plot_for(Date.today.month)
 send_data(png_data, :type => "image/png", :disposition => "inline")
end

send_file
def send_secret_file
 send_file("/files/secret_list")
 headers["Content-Description"] = "Top secret"
end

有些地方使用redirect_to代替render
redirect_to(:action => ‘display’)

redirect_to(options…)
redirect_to(path)
redirect_to(url)

Cookies and Sessions
Cookies只能存String
class CookiesController < ApplicationController
 def action_one
  cookies[:the_time] = Time.now.to_s
  redirect_to :action =>"action_two"
 end
 def action_two
  cookie_value = cookies[:the_time]
  render(:text => "The cookie says it is #{cookie_value}")
 end
end

cookies[:marsupial] = { :value => "wombat",
          :expires => 30.days.from_now,
          :path =>"/store" }
可用选项 :domain, :expires,:path, :secure, and :value

Sessions
保存model时要先预载:
class BlogController < ApplicationController
 model :user_preferences

设置session:
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:session_key] = ‘my_app’
可用选项:
:database_manager
:session_domain
:session_id
:session_key
:session_path
:session_secure
Session保存选择:
:database_manager => CGI::Session::PStore
  flat file (单服务器推荐)
:database_manager => CGI::Session::ActiveRecordStore
:database_manager => CGI::Session::DRbStore
:database_manager => CGI::Session::MemCacheStore

Flash用于在两个action传输暂时信息
flash.now用法实例:
class BlogController
 def display
  unless flash[:note]
   flash.now[:note] = "Welcome to my blog"
  end
  @article = Article.find(params[:id])
 end
end

flash.keep用法实例:
class SillyController
 def one
  flash[:note] = "Hello"
  redirect_to :action => "two"
 end
 def two
  flash.keep(:note)
  redirect_to :action => "three"
 end
 def three
  # flash[:note] => "Hello"
 render
 end
end

Filters
class BlogController < ApplicationController
 before_filter :authorize, :only => [ :delete, :edit_comment ]
 after_filter :log_access, :except => :rss
 # …
before_filter可用来替换全局页面中的字符,如{$title}
也可用来给页面 Zlib压缩
Around Filters可用来计算action用时

Verification
class BlogController < ApplicationController
 verify :only => :post_comment,
 :session => :user_id,
 :add_flash => { :note =>"You must log in to comment"},
 :redirect_to => :index
 # …
使用范围:
:only =>:name or [ :name, ... ]
:except =>:name or [ :name, ... ]
通过条件:
:flash =>:key or [ :key,... ]
:method =>:symbol or [ :symbol, ... ](:get, :post, :head, or :delete)
:params =>:key or [ :key,... ]
:session =>:key or [ :key,... ]
反应:
:add_flash =>hash
:redirect_to =>params

 GET Requests
 GET用来获取信息
 POST用来传输更改数据库的信息
 <%= link_to ‘删除评论’, { :action => ‘com_destroy’, :id => comment },
     :confirm =>"你确定要删除这则评论吗?",
     :post => true %>
使用forms和buttons

此条目发表在 Ruby on Rails 分类目录。将固定链接加入收藏夹。

发表评论