Leticia Esperon Leticia Esperon - 1 month ago 7
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:


Influencer.add_has_relation(Fan.find(2)).first.has_relation


But if I use COUNT like this:


Influencer.add_has_relation(Fan.find(2)).count


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:


Influencer.add_has_relation(Fan.find(2)).map(&:id).count


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

Answer

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

Comments