使用Chartkick Rails 4

时间:2016-03-29 20:15:43

标签: ruby-on-rails ruby ruby-on-rails-4 chartkick

我一直无法捕获与current_user相关的数据,然后绘制图表。我将发布我已编写的代码以及我在下面遇到的错误。

即使视图本身加载

,我也会收到以下错误
Error Loading Chart: Internal Server Error

Index.html.erb

   <div class="row">
    <div class="col-md-4">
      <%= line_chart analytic_posts_created_path(current_user) %>
    </div>
  </div>

Analytics_Controller.rb

class AnalyticsController < ApplicationController
  before_filter :authenticate_user!

  def index
    posts_created
  end

  def posts_created
    render json: current_user.posts.group_by_month(:created_at).count
  end

  private
  def set_user
    @user = User.friendly.find(params[:id])
  end
end

的routes.rb

resources :analytics, only: [:index] do
    get '/posts_created' => 'analytics#posts_created'
  end

Application.html.erb

<%= javascript_include_tag 'https://www.google.com/jsapi', 'chartkick' %>

服务器日志

Started GET "/analytics.john190" for 127.0.0.1 at 2016-03-29 17:46:50 -0400
Processing by AnalyticsController#index as 
  User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 5]]
  Post Load (0.0ms)  SELECT count(*) as count, strftime( "%Y-%m-01 00:00:00 UTC", created_at ) as date_slice FROM "Posts" WHERE "Posts"."user_id" = ? AND ("Posts"."created_at" IS NOT NULL) GROUP BY date_slice  ORDER BY "Posts"."created_at" DESC, date_slice  [["user_id", 5]]
Completed 200 OK in 10ms (Views: 6.0ms | ActiveRecord: 0.0ms)

1 个答案:

答案 0 :(得分:0)

我采用传统方法使用实例变量而不是JSON。 JSON方法会覆盖html视图。

analytics_controller.rb

def index
    @user_monthly_articles = current_user
    @user_monthly_articles.articles.group_by_year(:created_at).count
  end

index.html.erb

 <div class="row">
    <div class="col-md-4">
      <%= line_chart @user_monthly_articles %>
    </div>
  </div>