Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Arel for NOT EXISTS?

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
   )
 )
like image 343
neezer Avatar asked Aug 22 '11 19:08

neezer


1 Answers

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)
like image 165
Pedro Rolo Avatar answered Sep 20 '22 19:09

Pedro Rolo