marcamillion
marcamillion

Reputation: 33755

Rails select records using an array

I have this code in my ProfilesController#Index:

      @profiles = []
      profile_ids = current_user.ratings.order(speed: :desc).pluck(:profile_id)
      profile_ids.each do |id|
        @profiles << Profile.find(id)
      end

I tried doing this:

@profiles = current_user.ratings.order(speed: :desc).pluck(:profile_id).each do |id|
    Profile.find(id)
end

But for some reason, that would only put the value of :profile_id into @profiles and not the actual Profile(find(id)) like I want.

There a way to do this more elegantly?

Upvotes: 1

Views: 391

Answers (2)

Akash Agarwal
Akash Agarwal

Reputation: 2520

profile_ids = current_user.ratings.order(speed: :desc).pluck(:profile_id)
@profiles = Profile.where(:id => profile_ids)

The second line will search in Profile model with the given array profile_ids
It will generate a SQL like SELECT * FROM profile WHERE id IN (1,2,3..)

Edit: Another form: @profiles = Profile.find(profile_ids)

Upvotes: 0

Oscar Mederos
Oscar Mederos

Reputation: 29813

The problem with selecting the Profile IDs first, and then doing something like Profile.where(id: profile_ids).to_a is that you won't get the results in the expected order.

On the other hand, the main issue with your query is that you will be performing N+1 queries, N being the size of profile_ids. The following query should perform only two, and give you the profiles in the expected order:

profiles = current_user.ratings.order(speed: :desc).includes(:profile).map(&:profile)

More info about N+1 queries here

Upvotes: 3

Related Questions