0

I have a model Profile that has a onetoone with the model Interest. If I query an array of Profiles using where, how would I then get another separate array composed of the Interests associated with those originally queried Profiles?

Something like

@foundProfiles = Profile.where(field: data)

into

@foundInterests = @foundProfiles.Interest.all

this doesn't work, but that's the idea I'm trying to get at.

1 Answer 1

2

Make use of association:

@foundProfiles = Profile.includes(:interest).where(field: data)
# Eager load interest to avoid n + 1 queries

@foundInterests = @foundProfiles.map(&:interest)

EDIT

If you need to query further on the Interest records you can do something like:

@foundInterests = Interest.where(profile_id: @foundProfiles.map(&:id))

This will return you Interest records associated with @foundProfiles and you can chain where on it

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, I was in the dark about the map function.
It seems as though I can't do a follow up where on @foundInterests though... it gives me a no method where error
No you can't. it will return you array
Okay then. If I did a query of Interests, how would I then do another query (using some criteria) on the Profiles associated with those Interests? So that my final result is an array of desired Profiles? This is a slight reversal of the original question in terms of objects, but the key question is a the same. How would I do a query, and then do another query of the associated objects?
You can use ids
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.