0

I am trying to add a search functionality to my ruby on rails application. The search works fine but how can I add a validation so it displays when the search is empty?

I have tried adding required: true but that doesn't seem to do much.

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

I expect the output to be: 1. Search for particular topic 2. There is no topics within that field so a validation is displayed such as "no results found, please try again"

Krupa
  • 23
  • 5

2 Answers2

0

just update the code in controller as below so that you will get required records when search is present else all records if search params are not present.

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
Yarrabhumi
  • 36
  • 6
  • After adding this bit of code to the controller, the outcome is still coming out as blank. Am I able to add a validation in the controller such as "notice: "This topic does not exist, please try again." – Krupa Apr 09 '19 at 13:04
  • @krupa are there records in database? the thing is validations are different they are used to make a field as mandatory and to check weather the the input is as per requirements while you are inputing the data to database. but in index you just get the what ever data is present in database. – Yarrabhumi Apr 09 '19 at 13:22
  • @krupa updated my answer to display notice messages based on the data. If it works fine upvote the answer. – Yarrabhumi Apr 15 '19 at 12:42
0

You can add flash message in controller:

flash[:notice] = "No result found"

Your controller should be like:

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

For implementing flash message. Please see the link: https://stackoverflow.com/a/55590536/11094356

Pragya Sriharsh
  • 529
  • 3
  • 6