Newbie: Syntax for handling hash/arrays returned through SQL

I successfully created a few tables, controllers, models, etc., but
I’m hung up on taking the results that I receive back from a database
search. I started with higher level ActiveRecord usage and have gone
down to a raw sql query:

dailyReading = ActiveRecord::Base.connection.select_all(“select * from
dailyreadings where month = ‘3’ and day = ‘6’”)

I can see in the development.log that the query is fine. I’m simply
struggling with the syntax that will allow me to take the resultset
and use it. I’ve tried:

  • bookTitleStart = dailyReading[:start_book_title]
  • bookTitleStart = dailyReading(:start_book_title)
  • bookTitleStart = dailyReading[0]
  • etc.

I either get the whole array or nothing at all. The books and
resources I’ve seen so far haven’t addressed this level of direct sql
query/result usage. However, this has to be simple, but I’ve just not
figured it out yet.

I successfully created a few tables, controllers, models, etc., but
I’m hung up on taking the results that I receive back from a database
search. I started with higher level ActiveRecord usage and have gone
down to a raw sql query:

What was wrong with using ActiveRecord?

  • etc.
    To get the ‘start_book_title’ field of the first record returned you
    want:

dailyReading[0][‘start_book_title’]

-philip

What was wrong with using ActiveRecord?

Two things.

One is figuring out the syntax. I setup a Dailyreading controller and
the scaffolding code works fine. I’d like to call the view method on
the controller, but add constraints to essentially do what I did
through sql. While I had some things working, I decided to eliminate
that variable by going with pure sql. Now that you’ve help fix my
array issues, I can go back to it.

Second, the tables don’t have a standard relationship. Daily readings
involve a start point and an end point, so it doesn’t really fit the
standard relational model. Still, I can use much of what ActiveRecord
provides to avoid using too much sql and custom manipulation.

To get the ‘start_book_title’ field of the first record returned you want:

dailyReading[0][‘start_book_title’]

Perfect!

What was wrong with using ActiveRecord?

Two things.

One is figuring out the syntax. I setup a Dailyreading controller and

in your controller…

@daily_readings = DailyReading.find(:all,
:conditions => [“month = ? AND day = ?”, 3, 6],
:order => “month, day”)

you probably want to order by something…

in your view…

<% dailyReadings.each do |dr| %>
Start Book Title = <%= dr.start_book_title %>


<% end %>

You also get the advantage that (assuming start_book_title is a
datetime)
you get all the nice date/time functions rails/ruby provides…