ActiveRecord: error when trying to order results from a scope

断了今生、忘了曾经 提交于 2019-12-12 04:35:20

问题


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 order method.
  • The sorting is done by the Ransack gem, so I have no control over how it's done. I have used the order method as a way to reproduce the error that happens when trying to sort via Ransack sort_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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!