Topic: Simple Hash question

Hello to all,

I have a hash that is loaded with data from a table in my database,
using find(:all). It's pretty simple it has 3 key/value pairs (state/
city/population) and about 12 "elements".

What is the simplest way to print that information (only the states
and cities actually) out to the screen as an unordered list?

Or is there a better and simpler way than using hashes to achieve this?

Tank you very much!

Last edited by kronprinz311 (2008-05-30 09:36:57)

Re: Simple Hash question

kronprinz311 wrote:

I have a hash that is loaded with data from a table in my database,
using find(:all). It's pretty simple it has 3 key/value pairs (state/
city/population) and about 12 "elements".

... so it's rather an array of hashes?

[{:state => "bla",:city => "bla", :population => 10},{:state => "dong",:city => "ups", :population => 20},...]

find(:all) usually returns an array of activerecord objects ... where do the hashes come from?

a little code example would be helpful

Note: moved to Controller/Views

Re: Simple Hash question

You are right, it's actually an array of hashes.

city_list = City.find(:all)

It's coming from a table called cities that has 3 fields called "city", "state" and "population". An there are 12 records.

I think I'm getting close because in my view, I have this code:

<%city_list = City.find(:all)%>
       <ul>
           <% city_list.each do |i| %>
              <li>test</li>
           <% end %>
       </ul>

It prints out a list 12 items long with the word "test" for each.

Basically I just want to print out the 12 city names that are in my table to my City index view as an unordered list.

Last edited by kronprinz311 (2008-05-30 10:07:10)

Re: Simple Hash question

this is NOT an array of hashes, it's an array of ActiveRecord Objects.
each item in the array is an instance of the ActiveRecord::Base class and represents 1 row of the result.

<%city_list = City.find(:all)%>
<ul>
city_list.each do |i| %>
  <li><%=i.city%></li>
  <% end %>
</ul>

Re: Simple Hash question

Thanks Duplex,

that makes a,lot of sense. I am still very much a RoR "noob" smile But I very much appreciate the help!