Search code examples
javascriptrubydatabasesearchsequel

Creating a search function to search a Sequel Databse using a 'GET' method


I have an index.erb file created and within that file, I have code for a search bar:

<nav>
  <div class="nav-wrapper">
    <form>
      <div class="input-field">
        <input id="search" type="search" placeholder="Search..." required>
        <label for="search"><i class="mdi-action-search"></i></label>
        <i class="mdi-navigation-close"></i>
      </div>
    </form>
  </div>
</nav>

Ultimately I want to have this search bar to search my Sequel Database. I want to use a GET method in my app.rb file. However, I have a few obstacles.

Part 1 How can I save the text (that the user types into my search bar) into a variable that I can then use in my GET method (within my app.rb file)? In other words, how do I save what the user types into the search bar?

Part 2 Within my app.rb file, does it matter what my get method is called?

Part 3 I want to search my database using the .where() method. In my model.rb file, I defined a class Town. Within that migration, I have a collection of data. I want to search that data. So I'm guessing that my code in the app.rb file would be something like this (?):

@towns = Town.where(:name => @variable_from_part1)

Using the variable from PART 1 of my question, how would I go about searching my Sequel database? In other words, how would I search the database for what the user typed in and then display the result on my page?

Thank you!


Solution

  • PART 1 You create a name attribute within the <input/> field. So it would look something like this:

    <input name="search" type="text" placeholder="Search..."/>
    

    The most basic way of submitting this input is with an input field where the type=sumbit

    <input type="submit" value="Search"/>
    

    PART 2 It doesn't matter what you call the GET method. You could search a database using one, two, etc. methods. One way of doing it is to have a get '/search' do (or something like that) that directs the user to a webpage with the search bar. Then you could have that search bars action equal a different root like get '/' do. You could also just do it all under one GET root.

    PART 3 Then within the app.rb file, under the GET root (get '/' do), you would use params[:search] to save the text that was entered into your input field.

    get '/' do
        @towns = Town.where(:name => params[:search])
    end