Mysql 如何在rails 5.0中获得多态列类型上的分组项目总数?
背景:Mysql 如何在rails 5.0中获得多态列类型上的分组项目总数?,mysql,ruby-on-rails,postgresql,activerecord,ruby-on-rails-5,Mysql,Ruby On Rails,Postgresql,Activerecord,Ruby On Rails 5,背景: 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
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
编辑:
问题是如何使用Rails 5使其工作
可用于重新订购:
Image.group:imageable\u type.reorder:imageable\u type.count尝试以下查询:
SELECT COUNT(*) AS count_all, "images"."imageable_type" AS images_imageable_type
FROM "images" GROUP BY "images"."imageable_type"
ORDER BY 1 ASC
这个查询很有效,很好!但是有没有一种方法可以让ActiveRecord工作呢?基本上,您所做的错误是根据id对结果进行排序,而id并不是结果中所选列列表的一部分。因此,您在分组时会遇到错误。若要解决此问题,请同时在group by中添加id,或者对其中一个结果列使用order by
SELECT COUNT(*) AS count_all, "images"."imageable_type" AS images_imageable_type
FROM "images" GROUP BY "images"."imageable_type"
ORDER BY 1 ASC