DEV Community

Discussion on: Prefer returning chainable ActiveRecord objects

Collapse
 
k776 profile image
Kieran Pilkington • Edited

This is a good practice. I would recommend one addition though: only pull the columns from the DB that you need to fetch the right IDs, rather than everything. e.g.

Assuming shopper.can_order? is something like:

def can_order?(p)
  country == p.country
end
Enter fullscreen mode Exit fullscreen mode

then we only need to fetch two things: The ID (which we want to return), and the country which is used in can_order?.

store.products
  .where('price >= ?', 100)
  .select(:id, :country)
  .select{ |p| shopper.can_order?(p) }
  .map(&:id)
Enter fullscreen mode Exit fullscreen mode