通过rails将哈希传递给js以生成图表

Pass hash to js with rails to generate a chart

本文关键字:js rails 哈希传 通过      更新时间:2023-09-26

我正在尝试生成一个图表,其中包含每天注册到我的网站的新用户的数量。

我正在使用一个js,采用一个变量来填充图表,例如:

var pageviews = [
                    [1, randValue()],
                    [2, randValue()],
                    [3, 2 + randValue()],
                    [4, 3 + randValue()],
                    [5, 5 + randValue()],
                    [6, 10 + randValue()],
                    [7, 15 + randValue()],
                    [8, 20 + randValue()],
                    [9, 25 + randValue()],
                    [10, 30 + randValue()],
                    [11, 35 + randValue()],
                    [12, 25 + randValue()],
                    [13, 15 + randValue()],
                    [14, 20 + randValue()],
                    [15, 45 + randValue()],
                    [16, 50 + randValue()],
                    [17, 65 + randValue()],
                    [18, 70 + randValue()],
                    [19, 85 + randValue()],
                    [20, 80 + randValue()],
                    [21, 75 + randValue()],
                    [22, 80 + randValue()],
                    [23, 75 + randValue()],
                    [24, 70 + randValue()],
                    [25, 65 + randValue()],
                    [26, 75 + randValue()],
                    [27, 80 + randValue()],
                    [28, 85 + randValue()],
                    [29, 90 + randValue()],
                    [30, 95 + randValue()]
                ];

我有一个用户表,我需要创建一个哈希分组,并按日期计算上个月的用户。

:

User.group('date(created_at)').count

等等……第一个值是该月的几号,第二个值是该日提交注册的用户数。

当我有我的哈希值时,我如何将哈希值传递给JS?

您可以尝试将as_json填充到数据属性中:

<div id="page_views" data-users="<%= @user_registrations.as_json %>"></div>

假设我通过以下方式生成数据:

u = User.group("EXTRACT(DAY FROM created_at)").count.to_a
#=> [[26.0, 2], [27.0, 2]]

如果你的脚本是在.erb文件中,我可以直接将这个值传递给你的js变量(基于上面的示例输入)。

:

var pageviews = <%= u %>;