&tag(Rails/検証);
*目次 [#w60a64b3]
#contents
*関連ページ [#j1a32407]
-[[Rails]]
*参考情報 [#bd325948]

*一般的な検証の流れ [#o19460f3]
-モデルクラスにvalidatesメソッドの追加
#pre{{
class Item < ActiveRecord::Base
  validates :title, presence: true
end
}}
-controllerクラスでの検証
-scaffoldのデフォルト実装でも検証は行われる。
#pre{{
  def create
    @item = Item.new(item_params)

    respond_to do |format|
      if @item.save
        format.html { redirect_to @item, notice: 'Item was successfully created.' }
        format.json { render :show, status: :created, location: @item }
      else
        format.html { render :new }
        format.json { render json: @item.errors, status: :unprocessable_entity }
      end
    end
  end
}}
-ビューでは以下のようにエラーメッセージを表示する(もう少し分かりやすく表示する必要あり)
#pre{{
<%= form_for(@item) do |f| %>
    <% if @item.errors.any? %>
        <div id="error_explanation">
            <h2>エラーが発生しました :</h2>
            <ul>
                <% @item.errors.full_messages.each do |msg| %>
                    <li><%= msg %></li>
                <% end %>
            </ul>
        </div>
    <% end %>

    <div class="field">
        <%= f.label :title %><br>
        <%= f.text_field :title %>
    </div>
    <div class="field">
        <%= f.label :content %><br>
        <%= f.text_area :content %>
    </div>
    <div class="actions">
        <%= f.submit %>
    </div>
<% end %>

}}


*特別な検証 [#x54b3ed1]
**URLを検証する [#ude9b880]
-[[perfectline/validates_url:https://github.com/perfectline/validates_url]]
-[[Rails - gem validates_url 使ってみた - Qiita:http://qiita.com/mtsuge/items/366f44261c63b61db221]]
-Gemfileに追加
 gem "validate_url"
-モデルで検証
#pre{{
class User < ActiveRecord::Base
  validates :homepage, url: { allow_blank: true }
end
}}

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS