2014-06-16 37 views
0

我想加載一個模型,我試圖加載一個單一的記錄。Rails的急切加載其中字段匹配父項字段?

比方說:

Customer.includes(:sales).where('sales.created_at' => 'customer.last_sale_at') 

但不是工作SQL WHERE:

... WHERE "sales"."created_at" = "customer"."last_sale_at" 

count 
------- 
    1990 
(1 row) 

軌產生無效:

... WHERE "sales"."created_at" = 'customer.last_sale_at' 

ERROR: invalid input syntax for type timestamp: "last_sale_at" 
LINE 1: ...d" = "customers"."id" WHERE "sales"."created_at" = 'last_sale... 

我也試過:

Customer.includes(:sales).where('sales.created_at' => '"customer"."last_sale_at"') 
Customer.includes(:sales).where('sales.created_at' => :last_sale_at) 
Customer.includes(:sales).where('"sales"."created_at" = "customer"."last_sale_at"') 

其中產生了各種錯誤。

怎麼了?

編輯:我更新了這個問題,以便更加明瞭。

+2

last_sale_at是您在condiion中傳遞的日期對象嗎? –

+0

它是我渴望從中加載的模型中的字段。 – lmojzis

+0

在'WHERE'子句中,我自指'customer'模型的'last_sale_at'字段。 – lmojzis

回答

0

使用「包括」時,您不能調用條件,因爲記錄被載入渴望在一個單獨的查詢。您需要使用代替連接:

Customer.joins(:sales).where('sales.created_at = customers.last_sale_at') 

話雖這麼說,我建議你使用,你在創建客戶的實際關係指向最後一個銷售,即一個foreign_key略有不同的架構「last_sale_id」。

class Customer < ActiveRecord::Base 
    has_many :sales 
    belongs_to :last_sale, class_name: 'Sale' 
end 

在促銷中創建您可以更新客戶last_sale在回調中:

class Sale < ActiveRecord::Base 
    after_create :update_customers_last_sale 

    private 

    def update_customers_last_sale 
    customer.last_sale = self 
    customer.save! 
    end 
end 

有了這個結構,你可以做到這一點加載所有的客戶與他們的最後一次銷售:

Customer.includes(:last_sale) 
+0

謝謝。我是新來的鐵軌,並不知道有.joint()。 僅供參考:'last_sale_at'在這裏只是爲了排序而知道用戶何時進行了最後一次銷售。我想也能夠獲得最後一次銷售的鏈接。我能夠,但鐵路運行每個客戶不必要的查詢,我也想加載它。 好吧,再次感謝您的時間。你的答案真的是apperciated :) – lmojzis

+0

你可以指定條件在急切加載檢查了這一點http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations – Mandeep

1

您應該傳遞,而不是「last_sale_at」,它應該是類似下面的Date對象,

Customer.includes(:sales).where('sales.created_at' => Time.now) 
+0

但我需要在銷售時存儲在客戶的'last_sale_at'字段中。查看更新的問題... – lmojzis

0

如果你看看你的錯誤

ERROR: invalid input syntax for type timestamp: "last_sale_at"

它明確指出,有一個語法錯誤在您的查詢。活動記錄預計它是日期時間,因爲您的sales.created_at是時間戳,並且您正在將它替換爲字符串或某種其他類型(不是日期時間類型)。你需要傳入一個日期對象來讓你的查詢工作。

FIX

你需要確保你的last_sale_at場是datetime

+0

它是datetime,問題在where子句中。我需要在銷售時存儲在客戶的'last_sale_at'字段中。看到更新的問題... – lmojzis

+0

Rails應該產生'... WHERE「sales」。「created_at」=「customer」。「last_sale_at」',但是我得到'... WHERE「sales」。「created_at」 ='customer.last_sale_at'這是無稽之談。參考是在'customerController'中擁有自己的字段。 – lmojzis

+0

@lmojzis你的db中last_sale_at的類型是什麼? – Mandeep