views:

36

answers:

1

I'm new to rails and need some help with iterating through a sql result.

I have a method in my model that uses find_by:

def self.find_country()
  @countries = CountryTable.find_all_by_country_status('Y', :select => "country_name")
  @countries.each do |c|
    puts "#{c.inspect}"
  end
end

This is what I have in the view:

<%= select_tag "country", options_for_select(CountryTable.find_country) %>

Then I get this awkward #<CountryTable:0x30509bc> instead of the country name shown for each select option in the source:

<option value="#&lt;CountryTable:0x30509bc&gt;">#&lt;CountryTable:0x30509bc&gt;</option>
<option value="#&lt;CountryTable:0x3050944&gt;">#&lt;CountryTable:0x3050944&gt;</option>
<option value="#&lt;CountryTable:0x30508e0&gt;">#&lt;CountryTable:0x30508e0&gt;</option>

I'm so new to rails that I'm probably not even go about this right.

A: 

Even if you put a :select statement in the find statement it will still return objects of the model class (CountryTable). You need to extract the country_name attributes from the objects.

The best way to convert an array of objects by converting each object is to use map:

def self.find_country
  find_all_by_country_status('Y', :select => "country_name").map {|c| c.country_name }
end

This passes each country that find_all_by_country_status returns to the block. The block in turn returns the country name of the country. Then map combines those results into a new array and the method returns that.

As a side note, the name of your model should probably be just "Country", not "CountryTable". In Rails, models are named after the objects they represent. So if your model is "Country", each object (each row in the model's database table) represents a country.

mckeed
Thanks mckeed, that worked perfectly!