config/routes.rb
URL <===> config/routes.rb <===> パラメータ(@params)
- リクエストURLからパラメータを取得
コントローラの動き
対応するアクションが見つからない場合
- method_missing が定義されている場合
- method_missing を呼び出す
- レスポンスが生成されていない場合、テンプレートを呼び出す
- テンプレートが見つからなければ、'Template is missing'
- method_missing が定義されていない場合
- テンプレートを呼び出す
- テンプレートが見つからなければ、'Unknow action'
対応するアクションが見つかった場合
ActiveRecord のコールバック
実装の仕方
- インスタンスメソッドを定義
class Hoge < ActiveRecord::Base def before_save end end
- ブロック
class Hoge < ActiveRecord::Base before_save do |model| end end
- メソッドシンボル
class Hoge < ActiveRecord::Base before_save :foobar protected def foobar end end
- コールバックオブジェクト
コールバックオブジェクトは普通、app/modelsに置く。
class SinkEvents def before_validation(model) end def before_save(model) end def bofore_create(model) end end class Hoge < ActiveRecord::Base sink = SinkEvents.new before_save sink before_save sink before_create sink end
- オブザーバ
オブザーバは普通、app/modelsに置く。
class HogeObserver < ActiveRecord::Observer def before_save(model) end end または class XxxObserver < ActiveRecord::Observer observe Hoge, Huga def before_save(model) end end config/environment.rbで、 config.active_record.observers = :hoge_observer, :xxx_observer
ActionController のフィルタ
実装の仕方
- メソッドシンボル
class HogeController < ApplicationController before_filter :foobar private def foobar end end
- ブロック
class HogeController < ApplicationController before_filter do |controller| end end
- クラス
class HogeFilter def self.filter(controller) end end class HogeController < ApplicationController before_filter HogeFilter end
- aroundフィルタオブジェクト(aroundの場合のみ)
class HogeFilter def before(controller) end def after(controller) end end class HogeController < ApplicationController around_filter HogeController.new end
フィルタチェーン
- before, after, around の3つのフィルタがある。
- フィルタチェーンを抜けるには、false を返す。(nilではダメ)
- フィルタチェーンを抜けると、あとのチェーンは実行されない。
バリデーション
ActionController のバリデーション
ActionController のバリデーションエラーは、フラッシュに保存する。
class HogeController < ApplicationController verify :only => :アクション名, :session => :セッションキー, :add_flash => { :notice => '何かメッセージ' }, :redirect_to => { :action => 'index' } end
ActiveRecord のバリデーション
ActiveRecord のバリデーションエラーは、ActiveRecord::Validations モジュールで管理される。
Validations は ActiveRecord に Mixin される。
ActionView::Helpers::ActiveRecordHelper#error_messages_for でエラーを表示できる。
class Hoge < ActiveRecord::Base validates_xxx :messages => '何かメッセージ', :on => :save end