问题
I have the following model:
class Master < ActiveRecord::Base
belongs_to :language
has_and_belongs_to_many :users
scope :with_users_count, -> do
joins('LEFT OUTER JOIN masters_users on masters_users.master_id = masters.id')
.select('masters.*, COUNT(masters_users.user_id) as users_count')
.group('masters.id')
end
end
I'm trying to do:
Master.with_users_count.includes(:language).order('languages.name')
And the following error happens:
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "languages.id" must appear in the GROUP BY clause or be used in an aggregate function
Could you please advise on how to change the scope so this error is fixed?
Edit (additional info):
- The above code is meant to add the
quotes_count"attribute" to the results, so I can display the count of users for each master without N+1 and without the need for a counter cache (which seems to be buggy for HABTM). - The scope works just fine, the error appears when I call the
ordermethod. - The sorting is done by the Ransack gem, so I have no control over how it's done. I have used the
ordermethod as a way to reproduce the error that happens when trying to sort via Ransacksort_link, in an attempt to avoid adding more complexity to the question.
Thank you.
回答1:
You can have left_outer_join with languages also in the scope, it should remove the error while ordering because it will have language table joined in the sql query.
scope :with_users_count, -> do
joins('LEFT OUTER JOIN masters_users on masters_users.master_id = masters.id LEFT OUTER JOIN languages on languages.id = masters.language_id')
.select('masters.*, COUNT(masters_users.user_id) as users_count')
.group('masters.id')
end
来源:https://stackoverflow.com/questions/42029562/activerecord-error-when-trying-to-order-results-from-a-scope