Home > OS >  SQL equivalent to an active record query
SQL equivalent to an active record query

Time:01-20

I have a query I have made that works well

Team.all.map do |team|
   message = CoachFee.find_one(team_id: team.id).team_price_explanation[:prices]
end

My 'team' class is simply

{
         :id => 1,
    :team_id => 6,
 :created_at => nil,
  :player_id => nil,
 :updated_at => nil,
    :user_id => 1417
}

The team class has a one to many relationship with the CoachFee class.

The only problem is that I have well over 300,000 database values of CoachFee in my application, and so running this can take forever. (well over 4 minutes).

Are there any sql gurus out there that know quickly how to replace CoachFee.find_one(team_id: team.id) from Active Record to SQL?

Much thanks to anyone in advance!

CodePudding user response:

Give this a try:

CoachFee
  .where(id: CoachFee.select(CoachFee.arel_table[:id].minimum).group(:team_id))
  .map {|cf| cf.team_price_explanation[:prices]} 

This will result in the following SQL

SELECT 
  coach_fees.*
FROM 
  coach_fees 
WHERE 
  coach_fees.id IN ( 
    SELECT 
      MIN(coach_fees.id) 
    FROM 
      coach_fees
    GROUP BY 
      coach_fees.team_id
  )
  • Related