有人可以幫我查詢嗎?我有以下關聯:
class Customer < ApplicationRecord
has_many :customer_subscriptions, dependent: :destroy
end
class CustomerSubscription < ApplicationRecord
belongs_to :customer
end
我正在嘗試獲取所有客戶訂閱狀態均處于活動狀態的客戶。在這里,客戶訂閱的狀態為活動、取消和洗掉。我正在嘗試使用選擇查詢的 where 查詢。
uj5u.com熱心網友回復:
這是一種使用單個查詢的技術,該查詢回傳至少存在一個活動訂閱且不存在非活動訂閱的客戶。
Customer.
where(
CustomerSubscription.
where(status: 'active').
where(
CustomerSubscription.
arel_table[:customer_id].
eq(Customer.arel_table[:id])
).arel.exists).
where.not(
CustomerSubscription.
where.not(status: 'active').
where(
CustomerSubscription.
arel_table[:customer_id].
eq(Customer.arel_table[:id])
).arel.exists)
請注意,我可能忘記了那里的括號。它絕對可以用范圍來整理,所以看起來更多:
Customer.has_an_active_subscription.has_no_nonactive_subscriptions
uj5u.com熱心網友回復:
我會嘗試:
customer_ids_with_non_active_subscriptions =
CustomerSubscription.select(:customer_id).where.not(status: 'active')
Customer
.joins(:customer_subscriptions)
.where.not(customers: { id: customer_ids_with_non_active_subscriptions })
解釋:
- 首先,確定至少有一個非活動訂閱的客戶 ID 串列。
- 然后加載至少有一個訂閱(
joins部分)的所有客戶,但排除第一個串列中的客戶。
uj5u.com熱心網友回復:
獲取所有具有活動狀態的客戶訂閱,然后映射每個訂閱以獲取客戶
CustomerSubscription.where(status: 'active').map { |cs| cs.customer}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/414739.html
標籤:
上一篇:#<ActionView::Base:0x0000000010f748>的未定義方法`user_search_admin_path'
