我有一个名为coverage的模型,看起来像这样
1.9.3p429 :005 > Coverage.new
=> #<Coverage id: nil, postcode: nil, name: nil, created_at: nil, updated_at: nil>
以下是一个示例记录:
1.9.3p429 :006 > Coverage.find(10)
Coverage Load (7.3ms) SELECT "coverages".* FROM "coverages" WHERE "coverages"."id" = $1 LIMIT 1 [["id", 10]]
=> #<Coverage id: 10, postcode: "N10", name: "N10 - Muswell Hill", created_at: "2013-05-22 14:42:37", updated_at: "2013-05-22 14:42:37">
我有超过300个邮政编码,我想按照我在这个数组中的一些值对它们进行分组
group = ['N','E','EC','LS','TS']
所以我想做
@postcodes = Coverage.all
使用上面的数组运行它以获得以下哈希
@postcode_hash = { 'N' => [ '#Active Record for N1', '#Active Record for N2' ], 'E' => [ '#Active Record for E1', '#Active Record for E2' ] }
# note: not complete should contain all index from the above array
答案 0 :(得分:3)
您可以使用 .group_by{}
方法:
@postcodes = Coverage.all
@postcodes_hash = @postcodes.group_by{ |c| c.postcode.gsub(/[0-9]/, '') }
查看group_by
文档:
http://apidock.com/rails/Enumerable/group_by
上面有明确的版本:
@postcode_hash = {}
group = ['N','E','EC','LS','TS']
group.each{ |code| @postcode_hash[code] = [] }
@postcodes = Coverage.scoped # similar to .all but better
@postcodes.map do |coverage|
code = coverage.postcode.gsub(/[0-9]/, '') # takes off all the numbers of the postcode
@postcode_hash[code] << coverage if @postcode_hash[code]
end