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 分類目錄。將固定鏈接加入收藏夾。

發表評論