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)