0

I have implemented a simple search functionality for my rails 3 blog application. I want to validate it, in such a way, that with non-matching keywords, or when the search text field is blank, & when user clicks search button, it should display a message saying "your search criteria is invalid. Please try using valid keywords"

My Code is as follows :

In Post Model,

class Post < ActiveRecord::Base
attr_accessible :title, :body
validates_presence_of :search
validates :title, :presence => true, :uniqueness => true
validates :body, :presence => true, :uniqueness => true
  def self.search(search)
    if search
      where("title LIKE ? OR body LIKE ?","%#{search.strip}%","%#{search.strip}%")
    else
      scoped
    end
  end
end

In Post Controller,

 class PostsController < ApplicationController
  def index    
   @posts=Post.includes(:comments).search(params[:search])
   .paginate(per_page:2,page:params[:page]).order("created_at DESC")
  end
end

In Posts/index.html.erb (Views)

<div class = "search">
 <span>
  <%= form_tag(posts_path, :method => :get, :validate => true) do %>
    <p>
    <%= text_field_tag (:search), params[:search] %>
    <%= submit_tag 'Search' %>
  </br>
    <% if params[:search].blank? %>
    <%= flash[:error] = "Sorry... Your Search criteria didnt match. 
     Please try using  different keyword." %>
    <% else %>
    </p>
  <% end %>  
  </p>
  <% end %>
 </span>
</div>
4

2 に答える 2

2

params [:search]が空白かどうか、つまりテキストフィールドが空白かどうかを確認できます。

if params[:search].blank?
   flash[:notice] = "your search criteria is invalid. Please try using valid keywords"
   render 'index'
end

編集:

一致するキーワードがない場合:

if @posts.nil?
  flash[:notice] = "your search criteria is invalid. Please try using valid keywords"
  render 'index'
end
于 2012-11-05T07:06:17.710 に答える
1

検証のあるテーブルレスモデルにはActiveModelを使用します。たとえば、のようなモデルPostSearchに、他のモデルと同じように検証を追加できます。

モデル:

class PostSearch
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :input

  validates_presence_of :input
  validates_length_of :input, :maximum => 500

end

とあなたのフォーム:

<%= form_for PostSearch.new(), :url=>posts_path, :method=>:get, :validate=>true do |f| %>
  <p>
    <%= f.label :input %><br />
    <%= f.text_field :input %>
  </p>
  <p><%= f.submit "Search" %></p>
<% end %>

クライアント側の検証と組み合わせると、優れたユーザーエクスペリエンスが得られます。

ActiveModelに関する情報:

http://railscasts.com/episodes/219-active-model

Railscastのソースコード:

https://github.com/ryanb/railscasts-episodes/tree/master/episode-219/

于 2012-11-05T07:05:17.167 に答える