Associations with Chartkick & Rails

2019-07-29 07:02发布

问题:

I want to use chartkick to create a line graph of records, which belong to a planned task.

In other words: plantask has_many records

Records has two fields I'm interested in graphing. The created_at, which will be my X-axis, and data(An integer), which will be my Y-axis.

So far I've gotten pretty close. By inserting this into my view:

<%= line_chart @plantask.records.group_by_day(:created_at).sum(:data) %>

I can see that my x-axis is displaying perfectly. However, it appears that the y-axis is not loading the records :created_at field, but is loading the :created_at from within the plantask model. (All of my records are mapped to yesterday at 7:00pm) This seems strange to me. Any hints on what I've messed up? Thanks you guys.

回答1:

It turns out that I was approaching this problem the wrong way. Group by day with sum combines every task into one, and adds the value. What I really needed was this:

<%= line_chart @plantask.records.group(:created_at).sum(:data) %>