将 SQL 数据库中的信息显示到 ERB 网页中

Displaying information from a SQL DB into an ERB webpage

我正在创建一个带有搜索栏的程序,用于在我的项目中搜索我的 SQL 数据库。

Index.erb: 我的 index.erb 文件中有搜索栏的代码。

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

App.rb: 在我的app.rb 文件中,我使用params[:userInput] 获取用户在搜索栏中输入的信息。然后我通过 .where() 方法传递它以在我的数据库中搜索具有相同名称的项目。 (注意:我正在使用 sinatra 创建我的路线)。

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: 然后回到我的 erb 文件,我创建了一个 div 我想在其中显示信息(与用户最初输入的词)从数据库中收集。所以我做了:

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

但这只会在我的网页上显示标签 (#)。然后我转到 app.rb 文件并在 /submit 根目录下执行 @item.inspect。我回来了:

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

如何在我的网页上显示与 'apple' 关联的数据库中的实际信息?

经过研究,我发现这个问题有很多解决方案。我将使用一种基本和简单的方法。

Index.erb File 中,上面编写的代码 (<div> <%= @item %> </div>) 接近于预期的结果。不要只写 @item,你会写:

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