When I use a column alias in a query with find_by_sql, it doesn't appear to be set in the result objects, even when I add an attr_accessor for the property.
class Country < ActiveRecord::Base
attr_accessor :average_score
def self.sorted_by_average_score
sql = "SELECT country_id, AVG(score) AS average_score, countries.name " +
"FROM players " +
"INNER JOIN countries ON players.country_id = countries.id " +
"GROUP BY country_id "
Country.find_by_sql(sql)
end
end
I would expect to be able to do this:
countries = Country.sorted_by_average_score.first.average_score
...but it always returns nil, even though a value is definitely returned from the query.
Can anyone explain to me why the attribute isn't set in the object?