添加参数为ON子句包括左任何可能的方式连接在轨道上? [英] Any possible way to add parameters to ON clause on include left joins on rails?
问题描述
我有一个庞大的复杂的查询是这样的:
I have a huge complex query like this:
@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")
然后我想告诉所有的对象
只有 Important_things
创建的两个日期之间。
Then i want to show all Objects
and only Important_things
that were created at between two dates.
如果我把这个有其中,
条款我没有得到所有对象
,只有对象
,有 Important_things
知情日期之间。
If i put this on there where
clause i dont get all Objects
, only Objects
that has Important_things
between informed dates.
使用原始SQL中的解决办法是这样的:
A solution using raw sql was this:
SELECT *从对象左连接上important_things.object_id = objets.id之间'x'和important_things.created_at important_things'Y'
相反的:
SELECT *从对象左连接important_things上important_things.object_id = objets.id那里的important_things.created_at'X'和'Y'
我真的需要所有这些对象,我不希望在关联使用原始SQL,任何解决方法或一种可能性,参数传递给 ON
条款?
I really need all those objects and i don't want to use a raw SQL, any workaround or a possibility to pass parameters to the ON
clause on an association?
推荐答案
我做了一个丑陋的解决方法:
I did a ugly workaround:
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_at这些指定日期之间。
So this way i get all Parents
even if i dont have Children
created_at between those specified dates.
和它的最重要的部分,我有ActiveRecord的内部的所有对象。
And the most important part of it i have all objects inside the ActiveRecord.
但要小心,因为我没有搞砸cattr_accessor所以我必须设置每次在我搜索家长
。
But be careful because i did messed with cattr_accessor so i have to set everytime before i search for Parents
.
这篇关于添加参数为ON子句包括左任何可能的方式连接在轨道上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!