[英]Any possible way to add parameters to ON clause on include left joins 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
。
如果我將其放在where
子句中,則不會獲得所有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
因此,即使我在指定的日期之間沒有Children
created_at,我也會得到所有的Parents
。
最重要的是,我在ActiveRecord中擁有所有對象。
但是要小心,因為我確實把cattr_accessor弄亂了,所以在搜索“ Parents
之前必須每次都進行設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.