2016-02-13 56 views
0

我有一個表invoicesinvoicesbelongs_to :subscriptionsubscriptionbelongs_to :user。 A userhas_many :licenses。我需要兩個查詢,其中一個獲取在特定時間段內創建的所有invoices,其中包含licenses,因此那些licenses沒有特定的viewership_idComplex ActiveRecord加入

我能得到這個查詢正確的,那就是:

Invoice.joins(
    subscription: { 
    user: :licenses 
    } 
).where(
    # Other licenses during date range 
    licenses: { 
    created_at: date_range 
    } 
).where.not(
    licenses: { 
    viewership_id: Viewership.member.tier(1).first.id 
    } 
) 

現在,我需要一個查詢,得到所有的invoices不具有在特定時間段內創建的任何許可證。像這樣的東西(儘管這不工作):

Invoice.includes(
    subscription: { 
     user: :licenses 
    } 
).where(
    licenses: { 
     user_id: nil, 
     created_at: date_range # <-- removing this works, but is an incorrect query, 
          # because the user may have created other 
          # licenses outside of this date_range and 
          # that's alright--so querying without the 
          # date_range means i may miss some users who 
          # have licenses that just weren't created in 
          # the date_range 
    } 
) 
+0

我很難搞清楚你想要什麼,特別是那條評論。如果您可以創建一個顯示您嘗試實現的許可證的小型可視表,它可能會有所幫助。我也有點困惑 - 如果你想要的是許可證,爲什麼你不從許可證開始查詢? – max

+0

@max我說我需要一些發票,而不是許可證。我會盡力寫出一張圖 – trevorhinesley

+0

對不起,我的不好。您是否考慮在發票和許可證之間建立較少的切線關係?除了速度慢以外,你加入3張桌子的事實似乎是一種真正的代碼味道。 – max

回答

0

可能,這將幫助你

# Create a date range 
from_date = 1.months.ago 
to_date = Time.now 

@invoices = Invoice.joins(subscription: [user: :licenses]).where("licenses.created_at BETWEEN ? AND ? AND licenses.viewership_id !=?", from_date, to_date, Viewership.member.tier(1).first.id) 

爲了讓所有的invoices不具有在特定時間段內創建的任何許可證。

@invoices = Invoice.includes(subscription: [user: :licenses]).where("licenses.created_at NOT BETWEEN ? AND ?", from_date, to_date) 
+0

這就是我已經有的正確的查詢,我列出的第二個查詢是我無法正確的查詢。謝謝你 – trevorhinesley

+0

哦......我的壞。在這種情況下,您可以通過'licenses.created_at'搜索'Invoices'而不是給定的日期範圍。我更新答案。 –

+0

該查詢將查看它在此期間是否沒有創建任何許可證,但是它不會檢查它是否根本沒有任何許可證。我需要找到那些根本沒有任何許可證,或者有一些沒有在這些日期之間創建的許可證 – trevorhinesley