2013-03-15 40 views
0

我有這樣一個龐大複雜的查詢:任何可能的方法來添加ON子句的參數包括在鋼軌上的左連接?

@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,只有Objects有知情日期之間Important_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子句的可能性?

回答

0

我做了一個醜陋的解決方法:

class Parent < ActiveRecord::Base 
    cattr_accessor :dt_begin, dt_end 
    has_many :children, conditions: Proc.new { { created_at: (@@[email protected]@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

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 
+0

我知道這一點,但我不想寫所有我需要的連接:\ – 2013-03-18 18:40:25

+0

另外,我失去了之前完成的所有熱切加載...... – 2013-03-18 19:11:22

相關問題