向ON子句添加参数的任何可能方法都包括在rails上的左连接?

我有一个如此巨大的复杂查询:

@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") 

然后我想显示所有Objects和仅在两个日期之间创建的Important_things事件。

如果我把它放在那里我没有获得所有Objects子句,只有在知情日期之间具有Important_things Objects

使用原始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子句的可能性?

我这样做,

 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 

我做了一个丑陋的解决方法:

 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 

因此,即使我在这些指定日期之间没有创建子项,也可以通过这种方式获得所有Parents

其中最重要的部分是ActiveRecord中的所有对象。

但要小心,因为我确实搞砸cattr_accessor所以我必须在搜索Parents之前每次都设置。