Search code examples
rubydatabasesqlitesinatrasequel

Displaying information from a SQL DB into an ERB webpage


I am creating a program with a search bar that searches my SQL DB within my project.

Index.erb: I have the code for the search bar in my index.erb file.

<form method="get" action="/submit">
    <input placeholder="Search" type="text" name="userInput"/>
    <input type="submit" value="Search" />
</form>

App.rb: In myapp.rb file I use params[:userInput] to get the information that the user types into the search bar. Then I pass it through the .where() method to search my database for items with the same name. (Note: I'm using sinatra to create my routes).

get '/' do
    erb :index
end

get '/submit' do
    @item = Item.where(:name => params[:userInput]) #I created a table called `items` under my migration and a class called `Item` in my models folder
    # puts @item.inspect

    erb :index
end

Index.erb: Then back in my erb file, I created a div where I would like to display the information (with the same name as the word that the user typed in originally) that is gathered from the DB. So I did:

<div>
    <%= @item %>
</div>

But this only displays a hashtag on my webpage (#). So then I went to my app.rb file and did @item.inspect under the /submit root. I got back:

#<Sequel::SQLite::Dataset: "SELECT * FROM 'items' WHERE ('name' = 'apple')">

How can I display the actual information from my database that is associated with 'apple' onto my webpage?


Solution

  • As I researched, I found that there are many solutions to this problem. I'm going to use a basic and simplistic way.

    Within the Index.erb File, the code that is written above (<div> <%= @item %> </div>) is close to what the desired outcome is. Instead of just writing @item, you would write:

    <div>
        <% @item.each do |x| %> <!-- Or whatever variable you would like to pass -->
            <%= x[:the_id_of_your_hash] %> <!-- You can do this however many times you would like -->
        <% end %>
    </div>