Reputation: 834
I am trying to implement a simple search feature on my site. Currently, when I use my search bar it will work, but if the result is not found then it will pull up a blank page. I am using PostgreSQL
this is my form in recipes/index.html.erb
<%= form_with(url: recipes_path, method: :get, local: true) do |form| %>
<%= form.text_field(:term, {class: 'form-control', type:'search',
arialabel:'search', placeholder: 'search by recipe name'})%>
<%= form.submit 'Search', class: 'btn btn-dark bg-dark' %>
<% end %>
this is my controller index action in the recipes_controller.rb
def index
@recipes = if params[:term]
Recipe.where('name LIKE ?', "%#{params[:term]}")
else
Recipe.all
end
@categories = Category.all
end
I would like to redirect the user back to to the index view and display a message that says something like "the recipe was not found, please search for a different recipe."
Upvotes: 1
Views: 284
Reputation: 445
In your Index file,
<%= form_tag('/recepies/', :method => :get, :role => 'form') do %>
<%= text_field_tag :term, :class => "form-control", :placeholder => "Search"%>
<button class='glyphicon glyphicon-search' type="search">
</button>
<% end %>
In your controller,
def index
if params[:term].present?
@recipes = Recepie.all
@recipes = @recipes.find_term(params[:term].strip) if params[:term].present?
if @recipes.blank? {
flash[:notice] = 'the recipe was not found, please search for a different recipe.'
}
end
else
@recipes = Recepie.all
end
end
In your Model,
def self.find_term(term)
recipes = all
recipes = posts.where("recipes.term= ?", term)
end
Upvotes: 1
Reputation: 2365
when I use my search bar it will work, but if the result is not found then it will pull up a blank page.
So your search works but it has no results.
I would like to redirect the user back to to the index view and display a message that says something like "the recipe was not found, please search for a different recipe."
You could do something like @recipes.any?
to check if you got some results. If you check in the controller you can redirect and use the flash
for messages, or you can simply do it in the view and render the message.
PS: Not that you ask, but I really like to use ransack for complex search functionality.
Upvotes: 0