0

次のような非常に複雑なクエリがあります。

@objects = Object.joins({ x: :y }).includes(
  [:s, { x: { y: :z } }, { l: :m },:q, :w,
    { important_thing: 
      [:h, :v, :c,:l, :b, { :k [:u, :a] }]  
    }
  ]).where(conditions).order("x.foo, x.bar")

次に、2 つの日付の間に作成されたものObjectsだけをすべて表示したいと思います。Important_things

これをそこに置くと、whereすべてを取得することはできません。通知された日付の間にあるObjectsものだけです。ObjectsImportant_things

生のSQLを使用したソリューションは次のとおりです。

select * from objects left join important_things on important_things.object_id = objets.id and important_things.created_at between 'x' and 'y'

それ以外の:

select * from objects left join important_things on important_things.object_id = objets.id where important_things.created_at between 'x' and 'y'

これらすべてのオブジェクトが本当に必要であり、生の SQL を使用したくない、回避策、またはON関連付けの句にパラメーターを渡す可能性はありますか?

4

2 に答える 2

1

私はこれをします、

class VendorsRatings < ActiveRecord::Base

  def self.ratings(v_ids,sort = "DESC")

    joins("RIGHT OUTER JOIN vendors_lists v 
           ON v.vendor_id = vendors_ratings.vendor_id").where(conditions)

  end 

end
于 2013-03-15T20:42:11.700 に答える
0

私は醜い回避策を行いました:

class Parent < ActiveRecord::Base
  cattr_accessor :dt_begin, dt_end
  has_many :children, conditions: Proc.new { { created_at: (@@dt_begin..@@dt_end) } }
end

class MetasController < ApplicationController
  def index
    Parent.dt_begin = Date.parse(param[:dt_begin])
    Parent.dt_end = Date.parse(param[:dt_end])

    @parents = Parent.includes(:children).where("children.age = ?", params[:age])
  end
end

したがって、指定された日付の間にcreated_atParentsがなくても、この方法ですべてを取得できます。Children

そして最も重要な部分は、すべてのオブジェクトが ActiveRecord 内にあることです。

しかし、私は cattr_accessor をいじったので、検索する前に毎回設定する必要があるので注意してくださいParents

于 2013-05-14T19:42:46.917 に答える