【问题标题】:Creating a nested hash from ActiveRecord object in ruby从 ruby​​ 中的 ActiveRecord 对象创建嵌套哈希
【发布时间】:2015-06-22 09:25:08
【问题描述】:
require "active_record"

ActiveRecord::Base.establish_connection(
  :adapter  => 'mysql2',
  :database => '<db_name>',
  :username => '<username>',
  :password => '<password>',
  :host     => 'localhost')

ActiveRecord::Base.pluralize_table_names = false

class Location < ActiveRecord::Base
    has_many :location_channels
    has_many :channels, :through => :location_channels
end

class Channel < ActiveRecord::Base  
    has_many :location_channels
    has_many :locations, :through => :location_channels
end

class LocationChannel < ActiveRecord::Base  
    belongs_to :location
    belongs_to :channel
end

locations = Location.all

hash = {} # hash initialization

locations.each do |location|
    hash["location"] = location[:name]
        puts "#{location[:name]} has #{location.channels.size} channels:"
            location.channels.each do |channel|
                puts "--> #{channel[:name]}"
            end
        puts
end

puts hash

最终目标是创建一个JSON文件。

所以我决定从Hash object 创建JSON 会更容易。

与上面的代码一样,我可以通过名为 LocationChannel 类的 JOIN 表访问嵌套文档,并且我正在尝试弄清楚如何创建 Hash object 的样子:

{ 
  ["location" => "A", "channels" => {"1","2","3"}], 
  ["location" => "B", "channels" => {"1","2"}], 
  ["location" => "C", "channels" => {"4","5","6"}]
}

其中"A"、"B" 和 "C" - 位置名称和 "1"、"2" 等 - 代表频道名称。

并且当前代码只打印出最后一条记录,例如:

{"location"=>"A"}

如果上面的示例有误,请纠正我哈希应该是什么样子的。

更新 1

感谢@jonsnow 指出哈希格式。

哈希格式应该是:

{ :locations =>
    [
       { name: a, channels: [1,2,3]}, 
       { name: b, channels: [1,2]},
       { name: c, channels: [4,5,6]}
    ]
}

【问题讨论】:

  • 数组从不存储这样的元素["location" =&gt; "A", "channels" =&gt; {"1","2","3"}]。
  • 哈希永远不会像您期望的那样。您的哈希中没有 key =&gt; value 对
  • 第一对是"location" =&gt; "A",第二对是"channels" =&gt; ["1","2","3"]吗?
  • No oscar,你的 o/p 数组格式不正确,也许你的 o/p 应该是这样的,{ :locations => [{ name: a, channels: [1,2] }, { 名称:b,频道:[1,2] } ].
  • @jon snow - 谢谢,更新更正。

标签: ruby arrays json activerecord hash


【解决方案1】:

更新哈希的解决方案,

hash = { locations: [] } # hash initialization

locations.each do |location|
  hash[:locations] << { name: location.name,
  channels:  location.channels.pluck(:name) }
end

【讨论】:

  • in block in
    ': 未定义方法&lt;&lt;' for nil:NilClass (NoMethodError)
  • Opps,ans 已更新。将hash["locations"] 更改为hash[:locations]
  • 酷,工作! :) 非常感谢!我相信很多人都会从这个解决方案中受益。
猜你喜欢
  • 2021-02-03
  • 2014-12-06
  • 2014-02-07
  • 1970-01-01
  • 2018-08-24
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多