廃止
実行前にリクエストのバリデーション
説明
アクションの実行前にチェック
使い方
verify(引数.., オプション引数)
オプション
| オプション | 説明 |
| :params | パラメータがあるか |
| :session | セッションにキーがあるか |
| :flash | フラッシュの中に指摘したキーのデータあるか |
| :method | HTTPのメソッドが指定したものか |
| :xhr | アクションがAjaxから呼ばれたか |
| :add_flash | フラッシュにデータを追加 |
| :add_headers | HTTPのヘッダに「カラム名:値」を追加 |
| :redirect_to | 別のアクションにリダイレクト |
| :render | 別のアクションのテンプレートでレンダリング |
| :only | 適用するアクション |
| :except | 適応しないアクション |
例
セッションにuser_idがない場合は、indexにリダイレクト
verify session: "user_id", redirect_to: { action: "index" }
POSTでアクセスしていない場合は、indexにリダイレクト
verify method: :post, redirect_to: { action: "index" }
create, update, deleteアクション以外は、indexにリダイレクト
verify only: [:create, :update, :delete], :redirect_to { action: "index" }
ソースコード
キャッシュストアの設定
説明
キャッシュストアを設定
使い方
config.cache_store = キャッシュの種類
キャッシュの種類
| キャッシュの種類 | 説明 |
|---|---|
| :memory_store | プロセス内のメモリ |
| :file_store | ファイルシステム |
| :mem_cache_store | memcached |
| :null_store | キャッスをしない |
例
memcachedに保存
config.cache_store = :mem_cache_store
リクエストの前に実行する処理
説明
リクエストの前に実行する処理
使い方
ActionDispatch::Callbacks.before
例
ActionDispatch::Callbacks.before do
if Object.const_defined?(:Example)
if Example.const_defined?(:MyClass)
Example.send(:remove_const, :MyClass)
end
end
require 'example/my_class'
end
属性ハッシュを指定して更新
説明
条件に一致するモデルオブジェクトを更新
使い方
モデル.update_attributes(属性名, 値)
例
複数の項目を一度に変更・保存するメソッド
@user.update_attributes(:name, "hoge")
更新メソッドの種類
| メソッド | バリデーションの有無 |
|---|---|
| update | ○ |
| update_all | × |
| update_attributes | ○ |
| update_attribute | × |
ソースコード
全てのエラーメッセージのキーを取得
説明
全てのエラーメッセージのキーを取得
使い方
モデル.errors.keys()
例
person.errors.messages
#=> {:name=>["cannot be nil", "must be specified"]}
person.errors.keys
#=> [:name]
ソースコード
与えられたキー以外のすべてのエラーを削除
説明
与えられたキー以外のすべてのエラーを削除
使い方
モデル.errors.slice!(キー..)
例
person.errors.keys
#=> [:name, :age, :gender, :city]
person.errors.slice!(:age, :gender)
#=> { :name=>["cannot be nil"], :city=>["cannot be nil"] }
person.errors.keys
#=> [:age, :gender]
ソースコード
Errorsのハッシュのxml形式を取得
説明
Errorsのハッシュのxml形式を取得
使い方
モデル.errors.to_xml(オプション={})
例
person.errors.add(:name, :blank, message: "can't be blank")
person.errors.add(:name, :not_specified, message: "must be specified")
person.errors.to_xml
#=>
# <?xml version=\"1.0\" encoding=\"UTF-8\"?>
# <errors>
# <error>name can't be blank</error>
# <error>name must be specified</error>
# </errors>
ソースコード
すべてのエラーメッセージを取得
説明
すべてのエラーメッセージを取得
使い方
モデル.errors.values()
例
person.errors.messages
#=> {:name=>["cannot be nil", "must be specified"]}
person.errors.values
#=> [["cannot be nil", "must be specified"]]