我已经为我的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
在帖子/ 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>
我尝试这样做,但没有工作。任何人都可以帮助我实现我的目标。在此先感谢... –