10

I have a scope defined as follows:

scope :ignore_unavailable, lambda { 
  where([ "Item.id NOT IN (SELECT id FROM Cars WHERE Cars.status = 'NA'" ])
}

Currently its using hardcoded tables names. How can I improve it using frameworks like Arel ? Will appreciate any help here.

I am on Rails 3.2

2 Answers 2

13

Since the task description asks for an answer using AREL, I present following:

class Car
  scope :available, -> { where(arel_table[:status].not_in(['NA'])) }
end

class Item
  scope :available, -> { where(:id => Car.available) }
end

The sql should be something like the following:

SELECT [items].*
FROM [items]
WHERE [item].[id] IN (
    SELECT [cars].[id]
    FROM [cars]
    WHERE [car].[status] NOT IN ('NA')
  )

Obviously, rails 4 has the not scope, so this is a solution for rails 3.

The above code has two benefits:

  • It performs a single query
  • The table columns are correctly namespaced (unlike when using raw sql)
1
  • 1
    Thanks a lot ! I had problems with namespaces in a complex query, only Arel could help me here. :) Commented Jul 1, 2016 at 15:52
3

If you are using rails 4, one way would be

scope :ignore_unavailable, lambda {
  where.not(id: Car.where(:status => "NA").pluck(:id))
}

For rails 3

scope :ignore_unavailable, lambda {
  where("id not in (?)", Car.where(:status => "NA").pluck(:id))
}
6
  • unfortunately I am on rails 3.2 Commented Sep 5, 2014 at 19:25
  • Updated my answer for rails 3
    – usha
    Commented Sep 5, 2014 at 19:39
  • 2
    Thanks. This is great! One question though, Wont we be executing two SQL queries here instead of one like in original case ? Commented Sep 5, 2014 at 20:03
  • 1
    subqueries are actually bad. Performance wise having two queries might be better than having the subquery in your case. Read this blog, percona.com/blog/2010/10/25/mysql-limitations-part-3-subqueries
    – usha
    Commented Sep 5, 2014 at 21:07
  • @usha Subqueries are not “bad”. Loading an array of potentially millions of items out of laziness is “bad”.
    – coreyward
    Commented Sep 17, 2019 at 23:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.