如何在Hash和Array的帮助下按列对SQL结果进行分组?

时间:2015-01-26 05:11:07

标签: ruby-on-rails ruby arrays hash

我有以下查询:

select c.name,co.code from countries c
INNER JOIN continents co
on c.continent_code = co.code
INNER JOIN event_locations el
on el.location_id = c.id

Ruby代码:

 @records = Country.joins('
      INNER JOIN continents co
      on countries.continent_code = co.code
      INNER JOIN event_locations el
      on el.location_id = countries.id
  ').select('countries.name,co.code').order('co.code').all

产生的结果如下:

Pakistan    AS
Uganda  AF
United States   NA
Mexico  NA

现在在Rails结束时,我必须显示它:

<table>
  <tr>
    <td>AS</td><td>Pakistan</td>
  </tr>
  <tr>
    <td>NA</td><td>United States, Mexico</td>
  </tr>
</table>

我想使用相同的查询并考虑使用Hash和push into Array。在PHP中,我可以创建一个关联数组,并可以推送像:

这样的值
$myArray[$continent_name][]= $country_name

可以按键对值进行分组。我怎样才能在Rails / Ruby中实现它?

2 个答案:

答案 0 :(得分:0)

您编写的PHP的等价物是:

hash_with_default_array = Hash.new { |h, k| h[k] = [] }
@records.reduce(hash_with_default_array) do |result, record|
  result[record.code] << record.name
  result
end

但是,将数据从数据库传递到Web的确切方式取决于您使用的ORM(如果有)(ActiveRecord,Sequel,DataMapper,普通SQL ......)以及哪些HTML模板你正在使用的解决方案(如果有的话)(ERb,Slim,Haml,字符串连接...)

答案 1 :(得分:0)

group_by是你的朋友。

### Mock of ActiveRecord
Country = Struct.new(:name, :continent)
records = [
  Country.new("Pakistan", "AS"),
  Country.new("Uganda", "AF"),
  Country.new("United States", "NA"),
  Country.new("Mexico", "NA")
]

### The interesting bit
records.group_by(&:continent).each do |continent, countries|
  puts "#{continent}: #{countries.map(&:name).join(", ")}"
end