ruby-on-rails – 如何在Ruby中的.each中创建哈希散列
发布时间:2020-12-17 02:15:07 所属栏目:百科 来源:网络整理
导读:我正在研究一个跟踪不同事件及其状态的Rails应用程序. 这是我的状态模型: class Status ActiveRecord::Base attr_accessible :value has_many :eventsend 有一个界面可以添加其他状态类型. 我的事件模型如下所示: class Event ActiveRecord::Base attr_acc
我正在研究一个跟踪不同事件及其状态的Rails应用程序.
这是我的状态模型: class Status < ActiveRecord::Base attr_accessible :value has_many :events end 有一个界面可以添加其他状态类型. 我的事件模型如下所示: 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 例如,我有三种不同的状态值:停电,慢速,错误等. 有了这个,我可以做到: Event.outage 要么: Event.slow 并且我将获得具有该状态的所有事件的ActiveRecord :: Relation.这按预期工作. 我有一个视图,使用Highcharts动态生成一些图形.这是我的视图代码: <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 我想在哈希上调用每个来生成我的图表.这不会给我一个哈希,它给了我一个数组,就像Status.all本身一样. 解决方法
我就是这样做的,
Enumerable#each_with_object 和
Object#send :
hash = Status.select(:value).each_with_object({}) do |s,h| h[s.value.upcase] = Event.send s.value.downcase end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |