将哈希数组从Ruby on Rails输出到chart.js



当使用时间作为第二轴时,我在准备Ruby on Rails项目中的数据以用于图表.js时遇到了一些问题。

我已经查看了其他各种问题并设法非常接近,但是在以图表.js可以识别的格式导出数据时遇到问题。

感谢您的帮助!


问题

我需要以以下形式打印数据:

data: [
{"x":1567006282000,"y":145},        
{"x":1567009767000,"y":120},
{"x":1567009838000,"y":130}
]

但我目前得到以下信息:

data: [
{"x":1567006282000,"y":145}, 
{"x":1567009767000,"y":120}, 
{"x":1567009838000,"y":130}
]

当前尝试

我正在从控制器中创建如下数组,其中reading_timeobs.heart_rate是整数,我认为这是在创建一个哈希数组:

...
@hr.push ( { :x => reading_time, :y => obs.heart_rate  } )
...

然后,我在我的视图中打印它,转换为 json,以便理论上它可以与 javascript 库图表一起使用.js:

...
data: <%= @hr.to_json %>,
...

很确定我的问题在上面的两行中,但完整的代码在下面,以防需要。


完整代码

这就是我在我的控制器中创建(我认为(是哈希数组的方式:

def chart 
# Load observations for specific patient
@observations = Observation.where(:patient_id => params[:patient_id]);
# Prep arrays
@readings = []
@hr = []
# Cycle through all observations for this patient
@observations.each do |obs| 
# Convert created time to integer
# Multiple by 1000 as chart.js expects milliseconds while ruby uses seconds from UNIX epoch
reading_time = obs.created_at.to_i * 1000
# Add time to array so we can use this for the labels
@readings.push(reading_time)
# Create hash of time and observation value
hr_temp = {:x => reading_time , :y => obs.heart_rate }
# Push hash to the array
@hr.push( hr_temp )
# Repeat for other obserations - blood pressure, oxygen sats, etc
end
end

最后,我如何在我的观点中打印它:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js" integrity="sha256-xKeoJ50pzbUGkpQxDYHD7o7hxe0LaOGeguUidbq6vis=" crossorigin="anonymous"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
labels: <%= @readings %>,
datasets: [{
label: 'Heart Rate',
data: <%= @hr.to_json %>,
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
parser: 'X', // parse x values as unix timestamp
tooltipFormat: 'MMM Do, 'YY'
},
}]
}
}
});
</script>

工作示例

这是一个工作硬编码示例,显示了我的目标。

var ctx = document.getElementById('myChart').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Heart Rate',
data: [
{"x":1567006282000,"y":145},        
{"x":1567009767000,"y":120},
{"x":1567009838000,"y":130}
]
}]
},
options: {
scales: {
		xAxes: [{
			type: 'time',
			time: {
				parser: 'X', // parse x values as unix timestamp
				tooltipFormat: 'MMM Do, 'YY'
			},
		}]
	}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js" integrity="sha256-xKeoJ50pzbUGkpQxDYHD7o7hxe0LaOGeguUidbq6vis=" crossorigin="anonymous"></script>
<canvas id="myChart" width="400" height="400"></canvas>

由于渲染,它在后台使用to_s,这可能会导致从string类型对象呈现时出现一些编码问题。您应该尝试在@hr.to_json返回的对象上使用html_safe方法,例如@hr.to_json.html_safe

相关内容

  • 没有找到相关文章

最新更新