gpt4 book ai didi

ruby-on-rails - 如何在 Ruby 中的 .each 中创建一个散列的散列

转载 作者:数据小太阳 更新时间:2023-10-29 07:36:26 25 4
gpt4 key购买 nike

我正在开发一个跟踪不同事件及其状态的 Rails 应用程序。

这是我的状态模型:

class Status < ActiveRecord::Base
attr_accessible :value

has_many :events
end

有一个接口(interface)可以添加额外的状态类型。

我的 Event 模型如下所示:

class Event < ActiveRecord::Base
attr_accessible :status_id

belongs_to :status

class << self
Status.all.each do |status|
define_method(status.value.downcase) do
send("where", :status_id => Status.find_by_value(status.value.downcase))
end
end
end
end

例如,我有三个不同的状态值:OutageSlowError 等。

有了这个我可以做到:

Event.outage

或:

Event.slow

然后我将取回具有该状态的所有事件的 ActiveRecord::Relation。这按预期工作。

我有一个使用 Highcharts 动态生成一些图表的 View .这是我的 View 代码:

<script type="text/javascript" charset="utf-8">
$(function () {
new Highcharts.Chart({
chart: { renderTo: 'events_chart' },
title: { text: '' },
xAxis: { type: 'datetime' },
yAxis: {
title: { text: 'Event Count' },
min: 0,
tickInterval: 1
},
series:[
<% { "Events" => Event,
"Outages" => Event.outage,
"Slowdowns" => Event.slow,
"Errors" => Event.error,
"Restarts" => Event.restart }.each do |name, event| %>
{
name: "<%= name %>",
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%= @start_date.to_time.to_i * 1000 %>,
pointEnd: <%= @end_date.to_time.to_i * 1000 %>,
data: <%= (@start_date..@end_date).map { |date| event.reported_on(date).count}.inspect %>
},
<% end %>]
});
});
</script>

<div id="events_chart"></div>

我想使用数据库中的 Status 类型列表动态生成此哈希:

<% { 
"Outage" => Event.outage,
"Slow" => Event.slow,
"Error" => Event.error,
"Restart" => Event.restart }.each do |name, event|
%>

使用这样的东西:

hash = Status.all.each do |status|
hash.merge("#{status.value}" => Event) ||= {}
end

我想在散列上调用 each 来生成我的图表。但这并没有给我散列,而是给了我一个 Array,就像 Status.all 本身一样。

最佳答案

这就是我的做法,使用 Enumerable#each_with_objectObject#send :

hash = Status.select(:value).each_with_object({}) do |s, h|
h[s.value.upcase] = Event.send s.value.downcase
end

关于ruby-on-rails - 如何在 Ruby 中的 .each 中创建一个散列的散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14250010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com