Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Simple Search Functionality In Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.01k
    Comment on it

    Integrating Simple Search Functionality In Rails

    As we know that in almost all the web applications there is a search functionality. This functionality includes a search bar or search text box in which we can write the thing which we want to search and it gets us all the results which matches the text we have written in the search box. 

     

    So, We can integrate the same thing in our rails web application through a very simple procedure.

    First, we will create the html or front end for it in which we will create a form containing a search text box in which we will write the text we want to search and a submit button.

    For example, we are creating an ecommerce website and we want to search for a product in the search box. So the action of our form would be the index method of the products controller. 

     

    Our html code will look like this :

    <form action="<%= products_path %>">
      <input type="text" placeholder="So, What are you planning to buy today?" name="search_key">
      <button type="submit">Search</button>
    </form>

     

    Now the value of the text box will be sent to the products controller index method into params through name="search_key"

     

    Now in the products controller index method we will do this :

    class ProductsController < ApplicationController
      def index
        if params[:search_key]
          @products = Product.where("name LIKE ? OR description LIKE ?", 
          "%#{params[:search_key]}%", "%#{params[:search_key]}%")
        else
          @products = Product.all
        end
      end
    end

    This query will search the name and description columns in the Product table and if it finds any word matching with the search key then it will display the product on the index view. 

    So this is how we can integrate search functionality in our rails application.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: