kacy hulme
kacy hulme

Reputation: 141

searching in rails 4

i have examined other answers on here. not finding exact solution. controller/model/view below.

if someone searches for a project that does not exist, i need to display the notice "No search results match your search"

i tried adding and an elsif to the controller with params[:search].nil? and a flash

i also tried add an if/else to the model with the else returning a "No Search Results"

the controller

def index
  if params[:search]
   @projects = Project.search(params[:search].downcase).order("due_on ASC")
  else
   @projects = Project.all.order('due_on ASC')
  end
end

the model

def self.search(search)
  where("LOWER(project_name) LIKE ?", "%#{search}%")
end

the view

<p>
  <%= form_tag(projects_path, method: "get") do %>
  <%= text_field_tag :search, params[:search], placeholder: "Search" %>
  <%= submit_tag "Search", :name => nil %>
  <% end %>
</p>

Upvotes: 2

Views: 133

Answers (3)

Pavan
Pavan

Reputation: 33552

Setting a Flash notice in your controller code like this would work.

def index
  if params[:search]
   @projects = Project.search(params[:search].downcase).order("due_on ASC")
  else
   @projects = Project.all.order('due_on ASC')
  end
  if @projects.blank?
  flash.now[:notice] = "No Records Found for this search Result"
end

Upvotes: 0

Matheus Lima
Matheus Lima

Reputation: 2143

In your view:

<% if @projects.present? %>
  <%= do something here %>
<% else %>
  <p>No search results match your search</p>
<% end %>

Upvotes: 1

Justin
Justin

Reputation: 4940

How about adding it to your view??

<% if @projects.any? %>
  <%= render @projects %>
<% else %>
  <p>No search results match your search, <%= params[:search] %>.</p>
<% end %>

Upvotes: 3

Related Questions