我已经为我的 rails 3 博客应用程序实现了一个简单的搜索功能。我想以这样的方式验证它,即使用不匹配的关键字,或者当搜索文本字段为空白时,&当用户单击搜索按钮时,它应该显示一条消息“您的搜索条件无效。请尝试使用有效关键字"
我的代码如下:
在后期模型中,
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
在后控制器中,
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
在 Posts/index.html.erb (视图)
<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>