I’m using Rails 3 and the Highcharts JS Library for creating charts. And the setup works just fine. The only problem is that my data array also includes nil-data. But let me show you the code first. The following snippet defines the data for my Highchart.
data: <%= (30.days.ago.to_date..Date.today).map { |date| Health.total_on_weight(current_user.id, date).to_f}.compact %>
“Health” is the model and “total_on_weight” is a method which is defined in that model:
def self.total_on_weight(id, date)
where("user_id = ?", id).where("date(date) = ?",date).average(:weight) unless self.nil?
end
As you can see I already tried to create an array which contains only existing data. If there isn’t an entry in my database for the date, it shouldn’t be in the array, but as a matter of fact, it is.
I already tried do delete those entrys with the “compact” method and the “unless” method in my function. But there seems to be another problem which I can’t wrap my head around.
If anybody could explain to me why the nil-entries are still in my array or would have an sollution I would be very thankful.
OK, I narrowed the problem down:
If i leave the “to_f” in the function, as it now is, compact can’t erase the missing values because they are not nil, but 0. And the array looks like this:
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 90.0]
Then, if I leave out the “to_f”, the “compact” function can succesfully delete the missing values, which gives me an array like this:
[100.0, 100.0, 100.0, 90.0]
But the downside of this is, that Highcharts doesn’t has the right dates for my values anymore. It displays them right as I wanted, but the dates just don’t make any sense.
UPDATE:
I managed to fix the problem on my own. The data is now defined by:
data: [
<% @weights = Health.where("user_id = ?", current_user.id) %>
<% @weights.each do |weight| %>
<%= "[Date.UTC(" + weight.date.year.to_s + ", " + ( weight.date.month - 1 ).to_s + ", " + weight.date.day.to_s + ")" + ", " + weight.weight.to_f.round(2).to_s + " ],"%>
<% end %>
]
This definitely does the trick.
I managed to fix the problem on my own. The data is now defined by: