【问题标题】:Rails Active Record items partitioningRails Active Record 项目分区
【发布时间】:2012-08-08 19:09:06
【问题描述】:

所以,这是一个更简单的问题。我有一个像这样的活动记录对象:

Item
  --id
  --attribute 

我需要通过属性键拆分一个“Item”数组,所以我想像这样拆分各种数组。

[<#Item :id => 1, :attribute => 1>,<#Item :id => 4, :attribute => 1>,<#Item :id => 7, :attribute => 1>]
[<#Item :id => 2, :attribute => 2>,<#Item :id => 5, :attribute => 2>,<#Item :id => 8, :attribute => 2>]
[<#Item :id => 3, :attribute => 3>,<#Item :id => 6, :attribute => 3>,<#Item :id => 9, :attribute => 3>]

我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby arrays activerecord


    【解决方案1】:

    这应该给你一个数组数组,其中每个子数组都有相同的attribute

    Items.all.group_by(&:attribute).values
    

    编辑:由于您使用的是ActiveRecord,您可以在数据库中进行分组。我自己更像是一个DataMapper 的人,但这应该是大致的:

    Items.find(:all, group: 'attribute')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-05
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多