Ruby on Rails和geochart SQL查询

时间:2013-03-31 09:43:37

标签: ruby-on-rails ruby

我正在尝试在用户的模型上实现geochart,但我的助手方法上的SQL查询出现问题。用户模型将country作为其中一个字段。

我的问题是分组并将数据传递给js

users.js

google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawRegionsMap);

function drawRegionsMap() {
//    var data = google.visualization.arrayToDataTable([
//        ['Country', 'Popularity'],
//        ['Germany', 200],
//        ['United States', 300],
//        ['Brazil', 400],
//        ['Canada', 500],
//        ['France', 600],
//        ['RU', 700]
//    ]);

    var data = google.visualization.arrayToDataTable(['users_country_data']);

    var options = {};

    var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
    chart.draw(data, options);
};

index.html.rb

<%= content_tag :div, "", id: "chart_div", style: "width: 400px; height:200px;",  data: {users: users_country_data} %>

users.helpers.rb

  def users_country_data
      {
         Country: @users.group("country"),
         Popularity:  @users.count(:group => "country")
      }

  end

编辑。

enter image description here

1 个答案:

答案 0 :(得分:0)

对不起,你花了整整一天的时间,铁轨和红宝石应该比这更容易。

def users_country_data
  countries = @users.select('distinct country').map(&:country)
  countries.collect { |country| [country, @users.where(country: country).count] }.to_s
end

将为您提供js数组,例如:

[["Argentina", 100], ["USA", 200]]

如果您还想添加标题:

def users_country_data
  countries = @users.select('distinct country').map(&:country)
  countries.collect { |country| [country, @users.where(country: country).count] }.unshift(['Country', 'Popularity']).to_s
end

你得到错误的参数数量(1表示0)因为@users是一个用户数组,@ users是一个用户数组而不是ActiveRecord关系的任何理由?

编辑:我使用=而不是==进行比较

def users_country_data
  countries = @users.map(&:country).uniq
  countries.collect { |country| [country, @users.collect {|u| u.country == country}.count] }.to_s
end

聊天结束后,请记住您想要所有用户的图表:

def users_country_data
  countries = User.select('distinct country').map(&:country)
  countries.collect { |country| [country, User.where(country: country).count] }.unshift(['Country', 'Popularity']).to_s
end