Rails Search Returning Blank Page - ruby-on-rails

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."

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

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.

Related

RoR: Trying to search by ID number or License Number

hi so I'm trying to do 2 things, one of them is to basically redirect to a model's ID number so input is "1" and redirects to
localhost:3000/model/1
and the second part is actually doing a search. each model has a text field string for license_no and I want to be able to search and return results
currently, I am not sure how I would combine these into 1 search form if thats possible or if it would require 2 separate search forms
i have a search form with only the license_no field but it always returns no results found...
apologize that the model name isn't in singular, the guide I was using to learn RoR had it that way and everything worked, but I have so many references to renters in my project that it would be a while to find all of them
index.html.erb
<%= form_tag search_renters_path, method: get do |f| %>
<%= text_field_tag :license, nil, placeholder: "License Number" %>
<%= submit_tag 'Search', class: "btn-large" %>
<% end %>
models/renters.rb
class Renters < ActiveRecord::Base
validates_presence_of :license_no
def self.search(params)
renters = Renters.where("license_no LIKE?", "%#{params[:license]}%")
end
end
controller.rb
def search
#renter = Renters.search([params])
end
search.html.erb - snippet
<% if #renter.blank? %>
no results
<% else %>
#show results
<% end %>
editted code
models/renters.rb
def self.search(params)
license_query = "%#{params[:license]}%"
id_query = "%#{params[:id]}%"
renters = Renters.where("license_no LIKE ?", license_query) if params[:license].present?
renters = Renters.where("id LIKE ?", id_query) if params[:id].present?
end
controller
def search
#renter = Renters.search(params)
end
search form
<%= form_tag search_renters_path, method: :get do |f| %>
<%= text_field_tag :license, nil, placeholder: "Driver's License" %>
<%= text_field_tag :id, nil, placeholder: "ID number" %>
<% end %>
I'm trying to use the if present? statements to allow a user to decide whether to input ID No or License No. you don't need to input both just one. currently, if I search for a license no, it returns no results. but when I search for an ID, it returns the relevant result
you can do something like this if you are getting value on params[:licence] from your form submit on your controller action search
controller.rb
def search
#renter = Renters.search(params[:licence])
end
app/models/renters.rb
class Renters < ActiveRecord::Base
def self.search(query)
like_query = "%#{query}%"
renters = Renters.where("id LIKE ? OR license_no LIKE ?", like_query, like_query)
end
end

Generate search results for users by city in Rails 4

At the moment I am trying to create a search within a project to bring up users depending on their region. From what I understand, I basically need to place the search params in the controller, the self.search method in the model, and then the form in the view.
In another project, I have a search but it shows all the options above and use the search to filter out those which do not match. For this situation, I do not want to list any users in the beginning. I want to use the search bar and bring up any users that match within that view page. Additionally I use Devise for users if that does make a difference. Here are my three regions of code:
Model (user.rb):
def self.search(search)
where("state ILIKE ?", "%#{search}%")
end
Controller (welcome_controller.rb):
def index
#users = User.all.order("created_at DESC")
#newusers = User.all.order("created_at DESC").limit(5)
#differentlocations = User.all.group_by(&:state).count
render :layout => 'with_newest_members'
if params[:search]
#users = User.search(params[:search]).order("created_at DESC")
else
#users = User.all.order('created_at DESC')
end
end
View (find.html.erb):
<%= form_tag(find_path, :method => "get") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search Posts" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
Please let me know if you have any knowledge for me to help =) Any additional explanation would be greatly appreciated to help me understand, thank you!
Edit: I know I need to enter the results portion but I am confused about how/where to put it.
Joe
ANSWER:
The issue was in my controller because I had a render command prior to the search code. The controller should be:
def index
#users = User.all.order("created_at DESC")
#newusers = User.all.order("created_at DESC").limit(5)
#differentlocations = User.all.group_by(&:state).count
if params[:search]
#users = User.search(params[:search]).order("created_at DESC")
else
#users = User.all.order('created_at DESC')
end
render :layout => 'with_newest_members'
end
Fantastic =)
Two small things that might help:
1) In your Search model, I believe you have a typo in your search method. It should read as follows:
def self.search(search)
where("state LIKE ?", "%#{search}%")
end
You might also want to consider a more description name for your argument, such as state.
2) In your form, you don't need to explicitly write params[:search] anywhere. The params hash will be generated for you in the controller, with the name of the text_field as the key and the value inputted by the user as the value (see Ruby docs here). In this case, use :search as the name of the text_field_tag name.
<%= form_tag(find_path, :method => "get") do %>
<%= text_field_tag :search, placeholder: "Search Posts" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
More on FormHelpers here.

How do I validate text_field_tag used for searching purpose in rails 4.1

In homepage/index:
<%= form_tag :controller => 'hotels', :method => 'get' do %>
<%= text_field_tag :search, nil, :class => 'search-box'%>
<%= submit_tag "Search", :name=>'btnsearch' %>
<%end%>
In hotels_controller:
def index
#hotels= Hotel.where('hotel_location LIKE ?',"%#{params[:search]}%")
I am new to Rails and I am wondering that how to validate text_field_tag for nil value.Means if no record was found, then display the error message without redirecting to the hotel/index page.
Your question is somewhat paradoxial:
If no record was found, then display the error message without
redirecting to the hotel/index page
What you're asking is to perform the functionality which can only be achieved after you've sent a request to your app, and then display the message without redirecting?
Ajax
You'll probably be best using Ajax (Asynchronous Javascript and XML):
This is a way of sending & receiving requests outside the scope of the typical "HTTP" request (IE without reloading the page). This sounds like what you're looking for, as it will ensure you're able to return the data you want without redirecting to your index view again.
The importance of Ajax is that it provides many HTTP developers with the ability to create much more "organic" interaction structures within their applications (IE not having to reload the page every time you want to do something)
Ajax is very simple to implement - I'd recommend it for you:
--
Search
Here's what I'd do:
#app/assets/javascripts/application.js
$(document).on("ajax:success", "#search", function(status, data, xhr){
$(this).append(data);
});
#config/routes.rb
...
resources :hotels do
get :search, on: :collection
end
#app/views/homepage/index.html.erb
<%= form_tag hotels_search_path, method: :get, id: "search", remote: true do %>
<%= text_field_tag :search, nil, :class => 'search-box'%>
<%= submit_tag "Search", :name=>'btnsearch' %>
<% end %>
This will send a "get" request to your hotels_search path - which will allow you to do the following:
#app/models/hotel.rb
class Hotel < ActiveRecord::Base
def self.search search
results = where('hotel_location LIKE ?',"%#{search}%") if search
if results
return results
else
return "No Records"
end
end
end
#app/controllers/hotels_controller.rb
class HotelsController < ApplicationController
respond_to :js, :json, :html
def search
#hotels = Hotel.search params[:search]
respond_with #hotels, layout: false
end
end
how to validate text_field_tag for nil. if no record was found, then display the error message without redirecting to the hotel/index page.
Looks like you need to validate it on client side. You can checkout bootstrap validator which is really nice for using validations on client side.
If you want to write your own js to handle it then you can do something like this:
$(document).on("click","#your_btn_id",function(e){
var textValue = $(this).closest(".search-box").val();
if(textValue == ""){
e.preventDefault();
alert("Please enter some value");
}
});
Update:
You can also utilize HTML5 validations and won't need any js
<%= form_tag :controller => 'hotels', :method => 'get', :validate=>true do %>
<%= text_field_tag :search, nil, :class => 'search-box', :required => true %>
<%= submit_tag "Search", :name=>'btnsearch' %>
<%end%>
If you don't want to use ajax then you can do:
def index
#hotels= Hotel.where('hotel_location LIKE ?',"%#{params[:search]}%")
if #hotels
#your action
else
flash[:notice] = "Please enter a valid value"
render 'your_form_action'
end
end
Since Rails generates HTML5, I am sure you can leverage its required attribute to have Search text box as a mandatory field on your view page. Like this:
<%= form_tag :controller => 'hotels', :method => 'get' do %>
<%= text_field_tag :search, nil, :class => 'search-box', :required => true %>
<%= submit_tag "Search", :name=>'btnsearch' %>
<%end%>
Just to be assured that your controller doesn't get nil in params[:search], you can change controller's index action with:
before_filter :validate_search, :only => [:index]
def index
#hotels = Hotel.where('hotel_location LIKE ?',"%#{params[:search]}%")
if #hotels.present?
# other operation here!
else
redirect_to :back # will work only when referrer is present!
rescue ActionController::RedirectBackError
redirect_to root_path
end
end
def validate_search
if params[:search].nil?
redirect_to root_path, notice: 'Enter few characters to search!'
end
end

search form that redirects to search results page, rails

Hi how can I edit this code so when I click on search, I am redirected to specifed page not stay on the same?
<%= form_tag products_path, :method => 'get',:id => "products_search" do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %> </li>
<% end %>
You can do it like this:
<%= form_tag "http://www.stackoverflow.com/questions", :method => 'get',:id => "products_search" do %>
Put whatever you need in place of that URL.
for more info please look at the form_tag helper documentation
But if you need actually to be trough that path you were using, you have to use a redirect or a forwarding.
For using a forwarding just call the name of the next action near the end of that action yuo are calling.
Something like:
def another_action
...
end
def product
...
another_action
end
For using a redirect just do it like:
def products
redirect_to another_action
end

How to use link_to to pass value back to a search field and execute in RAILS, RoR?

I have a search field and button. When the user searches something like "cat" my view renders a bunch of related keywords such as "catnip", "cat toys", "cats" etc... each of these results are links, and are to pass the value of the string displayed back into the search to generate results for the selected link. For example:
User renders search page and searches for "cat"
view page renders results related to "cat" such as "catnip" "kittens"
User now clicks on "catnip"
View page renders results related to "catnip" such as "grass"
Is this possible with link_to? I'm lost and not quite sure what to do...
--
My Code:
SEARCH VIEW PAGE
<% form for(:search, url => search_path) do |f| %>
Search: <%= f.text_field :search %><br>
<%= f.submit "Search Keyword" %><p>
<% unless #keywords.nil? %>
<h3>Keyword Results</h3>
<% #keywords.each do |k| %>
<%= link_to k.name, :controller => "search", :action => "keywords", value => k.name %>
<% end %>
SEARCH CONTROLLER
def keywords
if request.post? then
#keywords = googlesearchapi(params[:search])
end
I want to pass the link_to value that the user clicks on as the :search parameter... thanks in advance for any advice~~
First of all, you want the link to be: "../search/keywords?search=catnip", to do this, modify the link_to as:
<%= link_to k.name, :controller => "search", :action => "keywords", :search => k.name %>
Then, you need to delete the line if request.post? then, otherwise it won't handle the requests coming from link_to, as it is a GET request (not POST).

Resources