Ruby on rails RubyonRails和SQL查询
我试图在用户的模型上实现,但在助手方法上的sql查询有问题。用户模型将国家/地区作为字段之一 我的问题是分组并将数据传递给js users.jsRuby on rails RubyonRails和SQL查询,ruby-on-rails,ruby,Ruby On Rails,Ruby,我试图在用户的模型上实现,但在助手方法上的sql查询有问题。用户模型将国家/地区作为字段之一 我的问题是分组并将数据传递给js users.js google.load('visualization', '1', {'packages': ['geochart']}); google.setOnLoadCallback(drawRegionsMap); function drawRegionsMap() { // var data = google.visualization.array
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} %>
def users_country_data
{
Country: @users.group("country"),
Popularity: @users.count(:group => "country")
}
end
编辑
很抱歉你花了整整一天的时间在这上面,rails和ruby应该比这更简单
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
由于@users是一个用户数组,您得到的参数数目(1代表0)错误,@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
谢谢你的回复。我真的很感激。但是“我得到了错误数量的参数(1代表0)”并且它指向的是国家=@users.select('distinct country')。map(&:country)\@用户应该是一个ActiveRecord关系,不确定为什么在\@users中得到一个用户数组以及为什么要对其进行计算,这非常无效,我添加了代码以使其与一个用户数组一起工作,但是您应该更新代码,以便activerecord关系中的\@用户可以通过让数据库引擎进行分组和计数来获得更高的速度。(如果\@users是一个用户数组,它将由ruby进行分组,而且速度会慢一些)谢谢,我接受你的回答,没有错误,但是图形还没有显示出来。但我认为你已经让我走得很远了。我会设法弄清楚为什么它没有显示地图。当我看HTML时,我得到了div数据用户=“[[“法国”,4],“加拿大”,4],“南非”,4],“id=“chart_div”style=“width:400px;height:500px;”>实际上,它显示了系统上所有国家的总用户数(4)。这是因为它逃避了HTML。尝试: