Leticia Esperon Leticia Esperon - 10 days ago 4x
SQL Question

Count not working on select with alias

I have a scope called add_has_relation
that does a left join with another table and renames with AS a field like this:

scope :add_has_relation, lambda { |fan|
joins("LEFT JOIN fan_influencers fi ON fi.influencer_id = influencers.id
AND fi.fan_id = #{fan.id}").select('influencers.*', 'fi.id AS has_relation') if fan.present?

If I use it, everything works great and I can use that field new field:


But if I use COUNT like this:


It fails with StatementInvalid because for some reason it is running this query:

SELECT COUNT(influencers.*, fi.id AS has_relation) FROM "inf...

and so I have to use it like this:


But I don't think it is neat. Is there a better way to do it?


You can use field parameters in the count method: Influencer.add_has_relation(Fan.find(2)).count(:id)