Search code examples
rubysqlitesqlite3-ruby

Don't work "db.results_as_hash = true" in Ruby


I connect to database and change db.results_as_hash to true

db = SQLite3::Database.new 'barbershop.sqlite'
db.results_as_hash = true

But it don't display hash, it is simple array. And don't work

<% @results.each do |row| %>
    <tr>
        <td><%= row['Name'] %></td> 

Working code is

<% @results.each do |row| %>
    <tr>
        <td><%= row[1] %></td>

Error is "no implicit conversion of String into Integer"

What's wrong?

Ruby 2.1.5p273, SQLite version 3.8.5, MacOS X Yosemite


Solution

  • From the repo you posted. You're not actually setting that flag. The code in your question is not the code you're running. There's no db variable, and you return on the first line, so the second never runs.

    def get_db
      return SQLite3::Database.new 'barbershop.sqlite'
      db.results_as_hash = true
    end
    

    I'm guessing that only compiles because the last line isn't executing. Try this:

    def get_db
      db = SQLite3::Database.new 'barbershop.sqlite'
      db.results_as_hash = true
      db
    end