2

我收到类似的错误

Mysql2::Error: Unknown column 'ctr' in 'having clause': SELECT COUNT(*) AS count_all, artists.id AS artists_id FROM `artists` INNER JOIN `photos` ON `photos`.`photoable_id` = `artists`.`id` AND `photos`.`photoable_type` = 'Artist' WHERE (admin_approved = 1) GROUP BY artists.id HAVING ctr >= 2

我的艺术家模型我写范围

scope :approved, where("admin_approved = ?", true)
scope :completed_profile, joins(:photos).select("artists.*,count(photos.id) as ctr").group("artists.id").having("ctr >= 2")

在我的控制器中我写

  def artists_completed_profile
     @artists = Artist.approved.completed_profile.page(params[:page]).per(10)
     @total_artists = @artists.size
  end 

注意: 当我在控制台中尝试时,我没有收到任何错误,但是当我在模型或控制器中写入时,我会收到此错误。

提前致谢

4

1 回答 1

4

您的分页中的某些内容.count很可能在尝试计算匹配总数以及总页数时执行。这.count将忽略.select您的范围的一部分,这就是您看到的原因:

SELECT COUNT(*) AS count_all, artists.id AS artists_id ...

被发送到 MySQL。您的ctr别名由您定义,.select因此.count's SQL 失败。您应该能够通过不在ctrHAVING 中使用来解决此问题,只需使用 raw count(photos.id)

scope :completed_profile, ...having("count(photos.id) >= 2")
于 2012-11-24T05:10:40.513 回答