如果搜索为空,如何添加验证?

时间:2019-04-09 10:44:13

标签: ruby-on-rails search

我正在尝试向我的ruby on rails应用程序添加搜索功能。搜索工作正常,但是如何添加验证,以便在搜索为空时显示呢?

我尝试添加required: true,但这似乎并没有太大作用。

index.html.erb:

<%= form_tag topics_path, :method => 'get' do %>
  <%= text_field_tag :search, params[:search], required: true %>
  <%= submit_tag "Search" %>   
<% end %

topics_controller:

def index
@topics = Topic.search(params[:search]).paginate(:page => params[:page], :per_page => 5)
end

topics.rb

def self.search(search)
        if search 
            where(["title LIKE ?","%#{search}%"])
        else
        all 
    end

我希望输出为: 1.搜索特定主题 2.该字段中没有主题,因此显示验证信息,例如“找不到结果,请重试”

2 个答案:

答案 0 :(得分:0)

只需按如下所示更新控制器中的代码,以便在存在搜索时获得所需的记录,否则在没有搜索参数的情况下获得所有记录。

def index
 if params[:search].present?
   @topics = Topic.search(params[:search]).paginate(:page => params[:page], :per_page => 5)
   flash[:notice] = "No records found based on the search." if @topics.blank?
 else
   @topics = Topic.all
   flash[:notice] = "No records found in Database." if @topics.blank?
 end
end

答案 1 :(得分:0)

您可以在控制器中添加Flash消息:

flash[:notice] = "No result found"

您的控制器应为:

def index
    @topics = Topic.search(params[:search]).paginate(:page => params[:page], :per_page => 5)
    if @topics.present?
         flash[:success] = "Any message!"
          //redirection
    else
          flash[:success] = "No result found"
           //redirection
    end
end

用于实现Flash消息。请查看链接:https://stackoverflow.com/a/55590536/11094356