Max Rose-Collins Max Rose-Collins - 7 months ago 18
Ruby Question

Ruby on Rails 4 count distinct with inner join

I have created a validation rule to limit the number of records a member can create.

class Engine < ActiveRecord::Base
validates :engine_code, presence: true
belongs_to :group
delegate :member, to: :group

validate :engines_within_limit, on: :create

def engines_within_limit
if self.member.engines(:reload).distinct.count(:engine_code) >= self.member.engine_limit
errors.add(:engine, "Exceeded engine limit")
end
end
end


The above doesn't work, specifically this part,
self.member.engines(:reload).distinct.count(:engine_code)


The query it produces is

SELECT "engines".* FROM "engines" INNER JOIN "groups" ON "engines"."group_id" = "groups"."id" WHERE "groups"."member_id" = $1 [["member_id", 22]]


and returns the count
0
which is wrong

Whereas the following

Engine.distinct.count(:engine_code)


produces the query

SELECT DISTINCT COUNT(DISTINCT "engines"."engine_code") FROM "engines"


and returns
3
which is correct

What am I doing wrong? It is the same query just with a join?

Answer

After doing long chat, we found the below query to work :

self.member
    .engines(:reload)
    .count("DISTINCT engine_code")