2017-07-19 48 views
-2

的背景:如何獲得rails 5.0中多態列類型的分組項目的總數?

create_table "images", force: :cascade do |t| 
    t.integer "imageable_id" 
    t.string "imageable_type" 
    ... 
end 

class PrivateGallery < ApplicationRecord 
    has_many :images, as: :imageable 
end 

class NationalGallery < ApplicationRecord 
    has_many :images, as: :imageable 
end 

class Image < ApplicationRecord 
    belongs_to :imageable, polymorphic: true 
end 

我想做一個簡單的查詢來獲取imageable_type的哈希值,並與該類型的行數 - Image.group(:imageable_type).count,但它返回:

SELECT COUNT(*) AS count_all, "images"."imageable_type" AS images_imageable_type FROM "images" GROUP BY "images"."imageable_type" ORDER BY id ASC 
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "images.id" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: ...mages" GROUP BY "images"."imageable_type" ORDER BY id ASC 

編輯:

問題是如何使它工作使用Rails 5.

工程與重新排序:

Image.group(:imageable_type).reorder(:imageable_type).count

回答

0

嘗試此查詢:

SELECT COUNT(*) AS count_all, "images"."imageable_type" AS images_imageable_type 
FROM "images" GROUP BY "images"."imageable_type" 
ORDER BY 1 ASC 
+0

此查詢的工作,太棒了!但有沒有辦法讓它與ActiveRecord一起工作? –

+0

基本上你在做什麼錯是基於'id'命令你的結果,這不是在結果中選擇的列列表的一部分。所以你一組一部分出錯。要解決這個問題,可以在組中添加id,也可以使用其中一個結果列的順序 –