sub where clause within the range of the current where clause

Viewed 19

I have two levels of dynamic filtering on a model. The first level is config driven, and the second level is user driven but should be a sub-filter for the config filter.

E.g. for the Post model, it works like this,

  • config_filter = {"name = 'test' and state in ['one', 'two']}
  • user_filter = {"name" = 'test1' and state in ['one', 'two', 'three']}
Post.where(....) # apply config filter
Post.where(...) # apply user filter but ignore 'test1' name and 'three' state as it is outside the scope of config filter.

Basically, I want users to search or filter within the scope of the main filter. I can use select, but because of pagination(limit and offset), the end page result might not be accurate(the page will show fewer items even though the overall item count is more than the page size, which will break the client pagination logic)

Any inputs to solve this the rails way will be of great help!

1 Answers

You can define some scope in the model

class Post < ApplicationRecord
  scope :available, -> { where.not(name: 'test1').where(state: %w[one two]) }
end

And then filter only records in this scope

Post.available.where(name: 'test1')
# => []

Post.available.where(state: 'three')
# => []

But without this scope you still can find records as well

Post.where(name: 'test1')
# => [#<Post ...>]
Related