获取ID列表从ActiveRecord模型的最佳实践 [英] Best practices for getting a list of IDs from an ActiveRecord model

查看:171
本文介绍了获取ID列表从ActiveRecord模型的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ActiveRecord模型语言,与列 ID short_ $ C $ ç(还有其他列,但他们不相关的这个问题)。我想创建一个将给予短codeS列表的方法,并返回ID的列表。我不关心联想,我只需要结束了一个数组,看起来像[1,2,3,...]

I have an ActiveRecord model Language, with columns id and short_code (there are other columns, but they are not relevant to this question). I want to create a method that will be given a list of short codes, and return a list of IDs. I do not care about associations, I just need to end up with an array that looks like [1, 2, 3, ...].

我首先想到的是做这样的事情

My first thought was to do something like

def get_ids_from_short_codes(*short_codes)
  Language.find_all_by_short_code(short_codes.flatten, :select => 'id').map(&:id)
end

但我不知道这是不必要的浪费时间/内存/处理。

but I'm not sure if that's needlessly wasting time/memory/processing.

我的问题是双重的:

  1. 有没有一种方法来运行一个ActiveRecord发现,将只返回一个特定的表列的一个阵列,而不是实例化对象?
  2. 如果是的话,它实际上是值得收集长度的数组的 N 的,而不是实例化的 N 的ActiveRecord对象?
  1. Is there a way to run an ActiveRecord find that will just return an array of a certain table column rather than instantiating objects?
  2. If so, would it actually be worthwhile to collect an array of length n rather than instantiating n ActiveRecord objects?

请注意,对于我的特定目的, N 的是大约200。

Note that for my specific purpose, n would be approximately 200.

推荐答案

老实说,对于200的记录,我就不会担心。当你到2000 20000,或200000的记录 - 那么你可以不用担心优化

Honestly, for 200 records, I wouldn't worry about it. When you get to 2000, 20,000, or 200,000 records - then you can worry about optimization.

请确保您有short_ code收录在表中。

Make sure you have short_code indexed in your table.

如果您仍然关心性能,看看在development.log看到数据库号码是什么特定的呼叫。您可以调节查询,看看它是如何影响日志中的表现。这应该给你一个表现的粗略估计。

If you are still concerned about performance, take a look at the development.log and see what the database numbers are for that particular call. You can adjust the query and see how it affects performance in the log. This should give you a rough estimate of performance.

这篇关于获取ID列表从ActiveRecord模型的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆