我在Ruby-on-Rails 4中构建应用程序。我设计了一个使用ActiveAdmin的管理站点。它工作的很好,但现在我想通过渲染一个局部图使用D3.js为我的索引页添加一个图表。 D3.js图书馆给我留下了非常深刻的印象,但我真的很新,因此我一直在尝试一些开发作为培训。在Rails中使用D3 ActiveAdmin
我还没有找到关于这个特定情况在互联网上的任何东西,所以我尝试从这个不错的教程:Using D3 in Rails。本教程中包含了D3.js库。 我的部分看起来像这样:
#app/views/admin/_chart.html.erb
<h3>HELLO WORLD!</h3>
<svg id="graph"></svg>
和管理user.file看起来是这样的:
#app/admin/user.rb
collection_action :data, method: :post do
respond_to do |format|
format.json {
render :json => [1,2,3,4,5]
}
end
end
然后,我有以下资产的脚本/ JavaScript的/ graph.js:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'data',
dataType: 'json',
success: function (data) {
draw(data);
},
error: function (result) {
error();
}
});
function draw(data) {
var color = d3.scale.category20b();
var width = 420,
barHeight = 20;
var x = d3.scale.linear()
.range([0, width])
.domain([0, d3.max(data)]);
var chart = d3.select("#graph")
.attr("width", width)
.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function (d, i) {
return "translate(0," + i * barHeight + ")";
});
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1)
.style("fill", function (d) {
return color(d);
});
bar.append("text")
.attr("x", function (d) {
return x(d) - 10;
})
.attr("y", barHeight/2)
.attr("dy", ".35em")
.style("fill", "white")
.text(function (d) {
return d;
});
}
function error() {
console.log("error");
}
当我显示页面时,部分页面正确加载(至少是标题),并且图表还有空间,但是它是空的。我在控制台中没有错误,所以我甚至可能不会上传graph.js文件,或者数据可能不会传输到聊天记录中。或两者。无论如何,我真的不知道为什么不明白,所以你的帮助将非常感激。 谢谢
S.
[编辑]
我在route.rb文件改变了路线:
resources :users do
collection do
...
get :data , :defaults => { :format => 'json' }
end
end
然后,我改变从图中的js文件的名称.js到users.js。于是,我改变的URL:“用户/数据”:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'users/data',
dataType: 'json',
success: function (data) {
draw(data);
},
error: function (result) {
error();
}
});
...
这样我可以显示在我的应用程序的索引页的图表。但是,我仍然无法在ActiveAdmin中显示它...我想知道是否因为我没有在ActiveAdmin(供应商文件夹内)中正确包含d3或者它是否是路由问题。