问题
How do you write a NOT EXISTS
in Arel? I'm having trouble translating this query into Arel:
SELECT * FROM deals
WHERE NOT EXISTS (
SELECT 1 FROM reward_deals
WHERE reward_deals.deal_id = deal.id
AND NOT (
reward_deals.awarding_type = 'deal'
AND reward_deals.deal_id = reward_deals.awarding_id
)
)
回答1:
Here is the answer, with strange names because I don't know how to give names for a domain that is for me unknown.
deals = Deal.arel_table
reward_deals = RewardDeal.arel_table
awarding_condition= reward_deals[:awarding_type].eq('deal')\
.and(reward_deals[:deal_id]\
.eq(reward_deals[:awarding_id]))
reward_deals_condition= reward_deals[:deal_id].eq(deals[:id])\
.and(awarding_condition.not)
Deal.where(RewardDeal.where(reward_deals_condition).exists.not)
来源:https://stackoverflow.com/questions/7152424/rails-3-arel-for-not-exists