Question

I am using ruby, sinatra, postrges and sequel. I have a database of UK House price data, one of the fields is price. I have experimented with numeric, int, money and real data types and it's all a disaster. Currently I am using numeric(8), the ruby code is:

result = DB[:house_data].select_group(:city).select_append{avg(:price)}.to_a.to_json

and the output is:

[{"city":"BOREHAMWOOD","avg":"0.3035E6"},{"city":"LEIGHTON BUZZARD","avg":"0.2089495E6"},{"city":"LEYBURN","avg":"0.37075E6"},{"city":"KEIGHLEY","avg":"0.68E5"},{"city":"TELFORD","avg":"0.122960714285714286E6"},{"city":"FILEY","avg":"0.18025E6"}]

which is, of course, hopeless as the numbers (for avg) are meaningless. I have tried different kinds of queries (again with avg) and the output is always similar. For example, the folowing always delivers an error message:

DB[:house_data].where(:city => 'LONDON').avg{:price}

and

DB[:house_data].where(:city => 'LONDON').where(:price > 100000)

both produce errors saying the function can't be carried out.

Where is the problem? The query or the data type in the postgres DB?

Était-ce utile?

La solution

The real problem here is that JSON doesn't have an arbitrary precision numeric type, and the ruby BigDecimal type by default uses scientific notation when converted to a string. As the database returns the avg computation as an arbitrary precision numeric, Sequel uses the ruby BigDecimal type for it.

You can add a BigDecimal#to_json method to set how BigDecimal instances should be converted to json.

Autres conseils

No show from anybody but I have solved it anyway. The issue was in the javascript rendering of the json data. The following is the way to do it:

addCommas(Math.round(this["avg"]),0)

the correct sequel query is:

result = DB[:house_data].group_and_count(:city).select_append{avg(:price)}.to_a.to_json
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top