[英]How to validate a search form in ruby on rails?
我为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
在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
在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>
您可以检查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
将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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.