从ActivereCord模型的收集中构建哈希
我正在尝试从模型中构建哈希。
这就是我想要构建的哈希类型。
{"United Sates" => "us", "United Kingdom" => "uk" .....}
现在,我尝试了很多方法,我只是四处走动。
这只是我的一些糟糕的尝试。
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
请一些建议。
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下是一些简单的替代方案:
由@Addicted 下面的评论提供:
Here are some one-liner alternatives:
Courtesy of @Addicted's comment below:
使用 Rails 4,您可以简单地执行以下操作:
我认为这是最佳选择,因为您不必加载一堆国家对象并迭代它们
Rails 3 上的 pluck 方法不允许多个属性,但您可以执行类似的操作:
With Rails 4 you could simply do:
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:
这些天我最喜欢的答案是使用
pluck
和to_h
来反转它们并首先获得代码
My favorite Answer these days is to use
pluck
andto_h
to reverse them and have the code first
定义国家/地区散列,然后从您的记录中填充它。
Define the countries hash then fill it from your records.