Search code examples
ruby-on-railsacts-as-taggable-onchartkick

Cumulative Chartkick Chart & Acts_As_Taggable_On


I'm currently having an issue getting a running total for a some data to be used on a Rails app with Chartkick and acts_as_taggable_on.

I want my users to search for items with tags, where my @items is:

@items = current_user.items.tagged_with(params[:query])

My x-axis is the created_at date for my items and my y axis is just a :result from my model, which is an integer. I want each item on the x-axis to be a running total including the last value (a positive or negative number).

If i set:

@chart = current_user.items.all

and use this for chartkick:

= line_chart @chart.group_by_day(:created_at).order("day asc").sum(:result).map { |x,y| { x => (@sum += y)} }.reduce({}, :merge)

The chart works great, BUT it's obviously not filtering what's being charted with my search params.

As soon as I change @chart to @items for my line chart which filters via the search params I get the error:

ERROR:  column reference "created_at" is ambiguous.

I've tried creating different scopes in my model to try to help the situation but it doesn't seem to help thus far.

I'd really appreciate any help.


Solution

  • Alright guys, I finally worked this out!

    Most answers around PG conflicts refer to .group() whereas I was looking at .group_by_day(:created_at). I fixed the ambiguous error by simply using:

    = line_chart @items.group_by_day('items.created_at').order("day asc").sum(:result).map { |x,y| { x => (@sum += y)} }.reduce({}, :merge)
    

    The only difference being passing 'items.created_at' as a string to group_by_day in order to define which created_at I was referring to.