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

标签 ruby-on-rails ruby ruby-on-rails-3.2

我正在开发一个跟踪不同事件及其状态的 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/

相关文章:

ruby-on-rails - 通过 Rails 发送的 HTML 电子邮件以附件形式到达

ruby-on-rails - 为什么 yard 不在 Rails 项目中显示私有(private)方法?

ruby-on-rails - 带有 execjs rails 的 Tomcat

ruby-on-rails-3 - 导轨 : Creating default records for has_many relationship

ruby-on-rails-3.2 - RestClient::ResourceNotFound(404 资源未找到):

ruby-on-rails - 什么数据库用于 15M 记录和快速搜索索引

ruby - Rbenv/Pow - Bundler::RubyVersionMismatch(启动应用程序时出错)

ruby - 如何在 ubuntu 19.04 上安装 rvm install 2.1.1

ruby - 如何检查字符串是否包含任何形式的撇号而不仅仅是单引号和 ruby

ruby-on-rails-3.2 - 在 Ruby on Rails 3.2.14/Ruby 2.0.0/PostgreSQL 9.2.4 中使用 activerecord 从序列中检索 nextval