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>