3

我有一个名为覆盖率的模型,看起来像这样

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
4

1 回答 1

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
于 2013-05-22T16:23:45.950 回答