【发布时间】:2012-11-05 06:55:36
【问题描述】:
我已经为我的 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>
【问题讨论】:
-
我试过了,但没有用。谁能帮我实现我的目标。在此先感谢...
标签: ruby-on-rails search post blogs message