【问题标题】:Graphing current_user data with Chartkick Rails 4使用 Chartkick Rails 4 绘制 current_user 数据
【发布时间】:2016-03-29 20:15:42
【问题描述】:

我一直无法捕获与 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)

【问题讨论】:

  • 你要渲染 json 吗?如果是,那么您应该使用json 而不是jsons
  • 我没有意识到有一个错字。感谢您的关注。我现在的问题是视图中显示的数字 1(表示按月创建的项目数),而不是折线图本身。
  • 打印折线图的代码在哪里?
  • 到目前为止我写的所有内容都在问题块内。
  • 在分析索引视图中。顺便说一句,它只显示数字。导航栏根本没有被渲染。

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


【解决方案1】:

我采用了使用实例变量而不是 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多