[英]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")
Then i want to show all Objects
and only Important_things
that were created at between two dates. 然后,我想显示所有
Objects
以及仅在两个日期之间创建的Important_things
。
If i put this on there where
clause i dont get all Objects
, only Objects
that has Important_things
between informed dates. 如果我将其放在
where
子句中,则不会获得所有Objects
,而只有在通知日期之间具有Important_things
Objects
。
A solution using raw sql was this: 使用原始sql的解决方案是这样的:
select * from objects left join important_things on important_things.object_id = objets.id and important_things.created_at between 'x' and 'y'
Instead of: 代替:
select * from objects left join important_things on important_things.object_id = objets.id where important_things.created_at between 'x' and 'y'
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? 我真的需要所有这些对象,并且我不想使用原始的SQL,任何解决方法或将参数传递给关联的
ON
子句的可能性?
I do this, 我这样做
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
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
So this way i get all Parents
even if i dont have Children
created_at between those specified dates. 因此,即使我在指定的日期之间没有
Children
created_at,我也会得到所有的Parents
。
And the most important part of it i have all objects inside the ActiveRecord. 最重要的是,我在ActiveRecord中拥有所有对象。
But be careful because i did messed with cattr_accessor so i have to set everytime before i search for Parents
. 但是要小心,因为我确实把cattr_accessor弄乱了,所以在搜索“
Parents
之前必须每次都进行设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.