【问题标题】:How to validate a search form in ruby on rails?如何在 ruby​​ on rails 中验证搜索表单?
【发布时间】: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


【解决方案1】:

您可以检查 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

【讨论】:

  • 关键词不匹配怎么办?就像他在搜索文本字段中输入一些垃圾输入一样:- dfkvjsdgndfk 那么它也应该返回相同的错误消息
【解决方案2】:

将 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 %>

将它与client side validations gem 搭配使用可以获得良好的用户体验。

ActiveModel 信息:

http://railscasts.com/episodes/219-active-model

Railscast 源代码:

https://github.com/ryanb/railscasts-episodes/tree/master/episode-219/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 2017-07-11
    • 2012-07-19
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    相关资源
    最近更新 更多