简体   繁体   English

在Rails中通过自定义方法对所有记录进行分组

[英]Group all records by custom method in Rails

I'd like to retrieve all records for a particular model and "index" each one by their name attribute. 我想检索特定模型的所有记录,并通过其name属性为每个记录“索引”。 The end result should be a Hash, where the keys are the name of the record, and the value is the record. 最终结果应为Hash,其中键是记录的名称,而值是记录。 I can do this easy enough with a method like 我可以用这样的方法很容易做到这一点

def self.all_by_name
  hash = {}
  all.each { |model| hash[model.name] = model }
  hash
end

Is there a way to do this with an active record query? 有没有一种方法可以通过活动记录查询来做到这一点?

all.group(:name) is what you need! all.group(:name)是您所需要的!

Some documentation: http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-group 一些文档: http : //api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-group

No, active record will either return an array or an active record relation. 不,活动记录将返回数组或活动记录关系。 You would have to massage it after into the data type of your choice. 您必须将其输入选择的数据类型后再进行处理。 ActiveRecor dcan return anything that SQL can normally return. ActiveRecor d可以返回SQL通常可以返回的任何内容。 However, you could do use the group method which is essentially the group by in SQL. 但是,您可以使用group方法,它实际上是SQL中的group by

I'm not sure in your case what your method should do because it seems like you are going to overwrite the value of your key if there are 2 objects with the same class. 我不确定在您的情况下您的方法应该做什么,因为如果有两个相同类的对象,您似乎将覆盖键的值。 Perhaps if you better defined what you need in an example I could help you better. 也许如果您在示例中更好地定义了所需内容,我可以为您提供更好的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM