[英]Rails - finding an object in an active record association by an attribute without issuing more queries
Very short question, I feel like the answer must be already on StackOverflow but I couldn't find it. 问题很简短,我觉得答案必须已经在StackOverflow上,但是我找不到它。
I have some incoming parameters. 我有一些传入的参数。 They each have a unique ID.
它们每个都有一个唯一的ID。
I query the database and get an active record association using something like: 我查询数据库,并使用类似以下内容的活动记录关联:
existing_things = current_user.things.where(uuid: [param_uuids])
This gives me an Active Record Association of those objects. 这给了我这些对象的活动记录关联。
However, what I later do is something like: 但是,我以后要做的是:
existing_things.where(uuid: some_specific_uuid)
Of course, when I run the above query, it issues an SQL statement. 当然,当我运行上述查询时,它会发出一条SQL语句。
What I would love to do is find an object in a pre-loaded Active Record array of objects, and return that object without issuing another query. 我想做的是在预加载的Active Record对象数组中找到一个对象,然后在不发出另一个查询的情况下返回该对象。
How should I do that? 我应该怎么做?
The same way you would if it was an ordinary array: Enumerable#find
. 如果是普通数组,则使用相同的方法:
Enumerable#find
。
existing_things.find { |t| t.uuid == some_specific_uuid }
(or select
if you're expecting more than one match) (或
select
是否要期待一场比赛)
If you're doing a lot of lookups like that, you might want to get a Hash involved: 如果您要进行大量类似的查找,则可能需要涉及哈希:
things_by_uuid = existing_things.index_by(&:uuid)
things_by_uuid[some_specific_uuid]
(again, if you're expecting more than one match per value, there's group_by
) (同样,如果您期望每个值有多个匹配项,则有
group_by
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.