Ruby-on-rails 从 ActiveRecord 模型集合构建哈希
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5519380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Build hash from collection of ActiveRecord Models
提问by Lee
I'm trying to build a hash from a Model.
我正在尝试从模型构建哈希。
This is the type of hash I want to build.
这是我想要构建的哈希类型。
{"United Sates" => "us", "United Kingdom" => "uk" .....}
I have tried so many ways now I'm just going around in circles.
我已经尝试了很多方法,现在我只是在兜兜转转。
Here are just some of my poor attempts.
这里只是我的一些糟糕的尝试。
select = Array.new
countries.each do |country|
# select.push({country.name => country.code })
# select[country.name][country.code]
end
h = {}
countries.each do |c|
# h[] = {c.name => c.code}
# h[] ||= {}
# h[][:name] = c.name
# h[][:code] = c.code
#h[r.grouping_id][:name] = r.name
# h[r.grouping_id][:description] = r.description
end
Please can some advise.
请给一些建议。
Thank You
谢谢你
回答by Phrogz
Here are some one-liner alternatives:
以下是一些单线替代品:
# Ruby 2.1+
name_to_code = countries.map{ |c| [c.name,c.code] }.to_h
# Ruby 1.8.7+
name_to_code = Hash[ countries.map{ |c| [c.name,c.code] } ]
# Ruby 1.8.6+
name_to_code = Hash[ *countries.map{ |c| [c.name,c.code] }.flatten ]
# Ruby 1.9+
name_to_code = {}.tap{ |h| countries.each{ |c| h[c.name] = c.code } }
# Ruby 1.9+
name_to_code = countries.to_a.each_with_object({}){ |c,h| h[c.name] = c.code }
Courtesy of @Addicted's comment below:
感谢@Addicted 在下面的评论:
# Ruby 1.8+
name_to_code = countries.inject({}){ |r,c| r.merge c.name=>c.code }
回答by guilleva
With Rails 4 you could simply do:
使用 Rails 4,您可以简单地执行以下操作:
country_codes = Hash[Country.pluck(:name, :code)]
Which I think is optimal because you don't have to load a bunch of country objects and iterate through them
我认为这是最佳的,因为您不必加载一堆国家对象并遍历它们
The pluck method on Rails 3 does not allow more than one attribute, but you could do something like:
Rails 3 上的 pluck 方法不允许多个属性,但您可以执行以下操作:
country_codes = Hash[Country.connection.select_rows(Country.select('name, code').to_sql)]
回答by Douglas F Shearer
Define the countries hash then fill it from your records.
定义国家/地区哈希,然后从您的记录中填充它。
countries_hash = {}
countries.each do |c|
countries_hash[c.name] = c.code
end
回答by Blair Anderson
My favorite Answer these days is to use pluckand to_h
这些天我最喜欢的答案是使用pluck和to_h
countries.pluck(:name, :code).to_h
# => {"United Sates" => "us", "United Kingdom" => "uk" .....}
to reverse them and have the code first
反转它们并首先获得代码
countries.pluck(:code, :name).to_h
# => {"us" => "United Sates", "uk" => "United Kingdom" .....}

