Includes no external join and count on child table

class Course < ActiveRecord::Base
  has_many :registrations

  delegate :count, to: :registrations, prefix: true
end

class Registration < ActiveRecord::Base
  belongs_to :course
end

In my view of the Courses indexes, I show the number of registrations for each entry. What is the best thing for? Usage includes (: registrations) with the delegated method registrations_count looking slower (in the console) than doing the database count in the main query.

I want to show all the entries, so I cannot use INNER join (). Using includes () as shown below gives an error PG::GroupingError: ERROR: column "registrations.id" must appear in the GROUP BY clause or be used in an aggregate function. I tried adding the where clause to: register for this, but it is still wrong:

Course.includes(:registrations).group("courses.id").select("courses.*, COUNT(registrations.id) as registrations_count")

Is it correct to specify the outer join as follows:

Course.joins('LEFT OUTER JOIN registrations ON registrations.course_id = courses.id').select('courses.*, COUNT(registrations.id) as registrations_count').group('courses.id')

, , , , , .

+4
1

. ?

counter_caching - association. - Rails - , .

belongs_to :course , counter_cache: true

@course.registrations_count

RailsCast

, includes vs joins,

.

Course.joins('LEFT OUTER JOIN registrations ON registrations.course_id = courses.id').select('courses.*, COUNT(registrations.id) as registrations_count').group('courses.id')
+4

Source: https://habr.com/ru/post/1537599/


All Articles