JapanRob
JapanRob

Reputation: 384

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.

I have some incoming parameters. They each have a unique 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.

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.

How should I do that?

Upvotes: 0

Views: 792

Answers (1)

matthewd
matthewd

Reputation: 4420

The same way you would if it was an ordinary array: Enumerable#find.

existing_things.find { |t| t.uuid == some_specific_uuid }

(or select if you're expecting more than one match)


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)

Upvotes: 1

Related Questions