Rails加入多个方法和范围

时间:2015-06-01 13:31:02

标签: ruby-on-rails-4 activerecord

我的rails应用程序提供了一系列服务,其定义如下:

service.rb

has_and_belongs_to_many :clients
has_many :translations, class_name: ServiceTranslation, dependent: :destroy

def with_translation(lang)
  includes(:translations)
      .where("service_translations.language_id=?", lang.id)
      .references(:service_translations)
end

scope :with_clients, -> { select("services.*, count(clients_services.service_id) as clients_count")
  .joins(:clients).group('services.id').order('clients_count desc') }

所以 with_translation 方法急切地加载服务的翻译(名称,内容等),范围 with_clients 确保服务按编号排序链接客户端(如果没有客户端链接到服务,则服务未显示)

在services_controller中单独调用时,这两种方法都有效:

services_controller.rb

class ServicesController < ApplicationController
  def index
    #@services = Service.with_clients.page(params[:page])
    #or
    @services = Service.with_translation(@lang).page(params[:page])
  end
end

一切都很好,花花公子,但我需要这两种方法一起工作,所以当我这样做时:

@services = Service.with_clients.with_translation(@lang).page(params[:page])

我收到此错误消息:

PG ::错误:错误:列“clients_count”不存在 第1行:SELECT DISTINCT“services”。“id”,clients_count AS alias_0 F ...

我尝试合并这两种方法,在控制器中创建整个查询,都是徒劳的...任何帮助都将不胜感激!

1 个答案:

答案 0 :(得分:1)

错误表明输出查询的列为clients_count,但它只是COUNT的别名。

尝试在rails console中运行范围并逐个分析日志中的查询:

你说这个有效吗

Service.with_clients

首先确保两个范围合并而没有分页正常工作

Service.with_clients.with_translation(@lang)

生成的查询应如下所示:

SELECT  DISTINCT "services"."id", count(clients_services.service_id) AS clients_count FROM "services" 
INNER JOIN "clients_services" ON "clients_services"."service_id" = "services"."id" 
INNER JOIN "clients" ON "clients"."id" = "clients_services"."client_id" 
LEFT OUTER JOIN "service_translations" ON "service_translations"."service_id" = "services"."id" 
WHERE (service_translations.language_id=2) 
GROUP BY services.id
ORDER BY clients_count desc