2012年8月26日日曜日

rails 3 検索でのバリデーション

railsではDBが存在しているバリデーションは簡単に実装出来ますが、そうでない場合は自分で検証処理をしなければならないと思っていました。いろいろ調べていくとactiverecordを継承しないmodelを作ると通常の検証処理を使える事がわかりました。
対応方法を以下に示します。参考にしたサイト


booksの中にsearchを追加する設定です。 routes.rb (search:検索画面表示用 create_search: 検索結果の判断 list:検索結果の表示)
  get "books/list"
  get "books/search"
  post "books/create_search"
  resources :books
books_contoller.rb
 
class BooksController < ApplicationController
....
#検索画面用
 def search
     @search = Search.new
     @search.title = "ruby" #デフォルト値のセット
  end
#バリデーション
  def create_search
    @search = Search.new(params[:search])
    flash[:params] = params[:search]
 #バリデーション
    if @search.valid?
       redirect_to :action => :list
    else
      render :action => :search
    end
  end
#結果の表示
  def list
    params = flash[:params]
    @list = Book.find_all_by_title  params[:title]
  end
end
search.erb
<%= form_for(@search,:url=>{:action => :create_search}) do |f| %>
  <% if @search.errors.any? %>
    

<%= pluralize(@search.errors.count, "") %> エラーが発生しています

    <% @search.errors.full_messages.each do |msg| %>
  • <%= only_error_message msg %>
  • <% end %>
<% end %>
<%= f.label :title,"タイトル" %>
<%= f.text_field :title %>
<%= f.submit %>
<% end %>
application_helper.rb
  
def only_error_message str
    arr = str.split(" ")
    arr.last
  end
search.rb
# coding: utf-8
#activerecordを継承していないモデル
class Search
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming
  
  attr_accessor :title
 #メッセージ半角スペースを入れて、メッセージ表示時にonly_error_message関数を使って、フィード名を削除
  validates_length_of :title, :maximum => 10 ,:message => " タイトルの最大文字数は10です"

  
  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  
  def persisted?
    false
  end
end

0 件のコメント:

コメントを投稿