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="#<CountryTable:0x30509bc>">#<CountryTable:0x30509bc></option>
<option value="#<CountryTable:0x3050944>">#<CountryTable:0x3050944></option>
<option value="#<CountryTable:0x30508e0>">#<CountryTable:0x30508e0></option>
I’m so new to rails that I’m probably not even go about this right.
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:This passes each country that
find_all_by_country_statusreturns to the block. The block in turn returns the country name of the country. Thenmapcombines 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.