bogdan / datagrid

Gem to create tables grids with sortable columns and filters
MIT License
1.02k stars 115 forks source link

Or filter #322

Closed Mziserman closed 7 months ago

Mziserman commented 7 months ago

Hello, I want to have a filter that uses OR.

For example with a table users with first_name and last_name, I would want a way to get user with SELECT * FROM users WHERE first_name = 'a' OR last_name = 'b'

according to the doc this should be doable like

@grid = UsersGrid.new(grid_params.slice(:first_name)) do |scope|
  scope
    .or(User.where(grid_params.slice(:last_name)))
    .page(params[:page])
end

but doing so does not use the or :

image

I also tried

@grid.reset_scope
@grid.scope { User.where(grid_params.slice(:first_name)).or(User.where(grid_params.slice(:last_name))).page(params[:page]) }

with a similar result. Am I misunderstanding the doc ?

bogdan commented 7 months ago

That's a little tricky to achieve a single scope block for multiple filters. I think the best way of doing it now is like this:

filter(:first_name, :string, dummy: true)
filter(:last_name, :string, allow_blank: true) do |scope, value, grid|
  scope.where(["first_name = ? OR last_name = ?", grid.first_name, value])
end

# OR like this with more code, but more clear
dynamic do
  scope do |s|
    s.where(["first_name = ? OR last_name = ?", first_name, last_name])
  end
end

filter(:first_name, :string, dummy: true)
filter(:last_name, :string, dummy: true)

That might seem counter intuitive to you, but I don't see a more elegant way of doing that even if we introduce custom DSL.

Mziserman commented 7 months ago

Thanks a lot !