Active Record Outer Left加入ElasticSearch结果(Rails 4.2)

时间:2015-10-27 07:29:07

标签: ruby-on-rails postgresql join activerecord elasticsearch

我在执行左外连接的模型上使用范围来合并SQL查询。我想使用ElasticSearch来查询这个模型,但是我无法弄清楚如何让连接与ES一起玩。

当我尝试将其添加为范围或手动将连接添加到ES搜索结果时,我收到此错误:

ActiveRecord::StatementInvalid at /families/search
PG::SyntaxError: ERROR:  syntax error at or near "AS"
LINE 1: ...NT(families.*, COALESCE(SUM(donations.amount), 0) AS total_r...
                                                         ^
: SELECT  COUNT(families.*, COALESCE(SUM(donations.amount), 0) AS total_raised) AS count_families_all_coalesce_sum_donations_amount_0_as_total_rai, families.id AS families_id FROM "families" LEFT OUTER JOIN donations ON families.id = donations.recipient_id WHERE "families"."id" = 56 GROUP BY families.id LIMIT 30 OFFSET 0

这是我的模特:

# app/models/family.rb

require 'elasticsearch/model'
require 'file_size_validator'

class Family < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

  has_many :donations, as: :recipient, dependent: :destroy

  scope :approved, -> { where(approved: true).order('families.created_at DESC') }
  scope :unapproved, -> { where approved: false }

  scope :visible, -> { where(visible: true).order('families.created_at DESC') }
  scope :hidden, -> { where(visible: false) }

  scope :include_total_raised, -> { joins('LEFT OUTER JOIN donations ON families.id = donations.recipient_id').select('families.*, COALESCE(SUM(donations.amount), 0) AS total_raised').group('families.id') }

这是我正在进行搜索的控制器:

class FamiliesController < ApplicationController
  before_action :set_family, only: [:edit, :show, :update, :approval_letter]

  load_and_authorize_resource
  before_action :require_login, only: [:edit, :update, :destroy, :approval_letter]

  def index
    @families = Family.approved.visible.include_total_raised.select(:id, :photo, :first_name, :last_name, :country, :slug).order('families.created_at DESC').page(params[:page]).per(30)
  end

  def search
    if params[:q].present?
      @families = Family.approved.visible.search(params[:q]).records.include_total_raised.page(params[:page]).per(30)
      render :index
    else
      redirect_to families_path
    end
  end

如果您需要任何其他信息,请与我们联系。

1 个答案:

答案 0 :(得分:0)

这最终成为我的HAML模板的问题:

%h2= pluralize(@families.length, 'Adopting family')

该行试图count @families ivar导致一些问题与Kaminari&amp;加入。当我评论出这条线路时,它运行得很好,但我仍然希望显示找到了多少搜索结果。所以我刚刚将count更改为length,效果很好。