How to make a ChartKick line chart with Rails associations?

230 Views Asked by At

I'm struggling with formatting my ruby code to get the kind of chart I want. I'm making a Rails 6 app with a few layers of associations between tables.
I have:

  • Each Headline has_one Article
  • Each Article has_one Sentiment
  • Sentiment table has a score column

The Chart I want to build will simply be X-axis = Headline.created_at, Y-axis headline.article.sentiment.score

CONTROLLER

@headlines = Headline.where("created_at = ?", Date.today)

VIEW CODE

<%= line_chart @headlines.group_by_day(:created_at).count %>

How do I get the Y-Axis to be 'score' instead of 'count'?

THANK YOU.

1

There are 1 best solutions below

0
On

It depends how you did setup the relationships of your models. If you have a relationship in Headline to Sentiment like this

class Headline
  has_one :article
  has_one :sentiment, through: :article
end

You can simply do something like this

@headlines.each_with_object({}) do |headline, result|
  result[headline.id] = headline.sentiment&.score
end
# { 1: 2, 3: 4}

You should include the article and sentiment in your initial query otherwise you will have a n+1 query like this

Headline.includes(:article, :sentiment).where("created_at = ?", Date.today)

There is probably a more performant way to group inline in SQL but this should do.