我有一个rails应用程序,我正在创建一个highcharts折线图来比较2个行业,电信和农业的股票,同时跟随this,ryan bates highstocks视频。
图表将在stock_quotes的index.html.erb视图中输出,其中highcharts的javascipt代码如下:
<div id="quotes_chart", style="width=560px; height:300px;">
$(function(){
new HighCharts.Chart(
chart: {
renderTo: "quotes_chart"
},
title: {
text: "Daily trades"
},
xAxis: {
type: "datetime"
},
yAxis: {
title: {
text: "Shillings"
}
},
tooltip: {
formatter: function(){
return HighCharts.dateFormat("%B %e, %Y", this.x) + ': ' + "Kshs" + Highcharts.numberFormat(this.y, 2);
}
},
series: [
<% { "Telecommunication" => StockQuote.telecomm, "Agriculture" => StockQuote.agric }.each do |name, prices|
%>
{
name: <%= name %>
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%= 2.weeks.ago.to_i * 1000 %>,
data: <%= (2.weeks.ago.to_date..Date.today).map { |date| StockQuote.price_on(date).to_f}.inspect%>
},
<% end %>]
});
});
</div>
模型 stock_quote.rb 如下:
scope :agric, where(category: "Agriculture")
scope :telecomm, where(category: "Telecommunication")
def self.price_on(date)
where("date(published_at) = ?", date).sum(:total_price)
end
这是stock_quotes div上输出的内容:
$(function(){ new HighCharts.Chart( chart: { renderTo: "quotes_chart" }, title: { text: "Daily trades" }, xAxis: { type: "datetime" }, yAxis: { title: { text: "Shillings" } }, tooltip: { formatter: function(){ return HighCharts.dateFormat("%B %e, %Y", this.x) + ': ' + "Kshs" + Highcharts.numberFormat(this.y, 2); } }, series: [ { name: Telecommunication pointInterval: 86400000, pointStart: 1398157330000, data: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 554.0] }, { name: Agriculture pointInterval: 86400000, pointStart: 1398157330000, data: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 554.0] }, ] }); });
答案 0 :(得分:3)
看rails 4 scope syntax 代替:
scope :agric, where(category: "Agriculture")
scope :telecomm, where(category: "Telecommunication")
使用:
scope :agric, -> { where(category: "Agriculture") }
scope :telecomm, -> { where(category: "Telecommunication") }
答案 1 :(得分:0)
您的范围定义必须是proc对象,而不是plain where语句。这是因为它们需要在范围的实际查询期间进行评估,而不是在类的初始设置期间进行评估。因此,请在您的模型中使用它:
scope :agric, -> { where(category: "Agriculture") }
scope :telecomm, -> { where(category: "Telecommunication") }