Mysql2 ::错误:'having子句'中的未知列'ctr'

时间:2012-11-24 04:54:14

标签: mysql ruby-on-rails ruby-on-rails-3.2 rails-activerecord

我收到错误

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 

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

提前致谢

1 个答案:

答案 0 :(得分:4)

您的分页中的某些内容正在执行.count,最有可能的是它会尝试计算匹配的总数,从而计算出总页数。 .count会忽略范围的.select部分,这就是您看到的原因:

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

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

scope :completed_profile, ...having("count(photos.id) >= 2")