0

I'm using Lupa for filtering (Lupa is framework independent, easy to test, benchmarks well against has_scope, etc.).

How can I chain scopes with OR logic in Lupa? This works great when the params are known ahead of time, but not when the filters are user-determined.

Perhaps the solution is in the dates_between section of the docs, but I cannot seem to figure it out.

I have a form that allows users to select the gender of an animal - male, female - using checkboxes. I want users to be able to check one, the other, or both and return the intuitive result.

Community
  • 1
  • 1
brntsllvn
  • 931
  • 11
  • 18

1 Answers1

0

Lupa's author's blog (@edelpero) nudged me in the right direction, but I feel either I am misunderstanding something or the docs might be improved (probably the former). Maybe some type-o's below as I'm simplifying from an app I'm kicking through, but here is a solution:

form

= form_tag pups_path, method: :get do
  = check_box_tag      'male',   'm'
  = check_box_tag      'female', 'f'
  # add a hidden field so that the gender method in the scope class is called
  = hidden_field_tag   'gender', 'anything' # tag must have a value
= submit_tag :search

controller

class PupsController < ApplicationController

def index
  @pups = PupSearch.new(Pup.all).search(search_params)
end

protected
    def search_params
      params.permit(:male, :female, :gender) # permit all three 
    end

end

scope class

class WalkSearch < Lupa::Search

  class Scope
    def male
      # leave blank to avoid chaining; handled in gender below
    end

    def female
      # leave blank to avoid chaining; handled in gender below
    end

    def gender
      # standard procedure for OR logic
      scope.joins(:pup).where('pups.male_female' => [
        search_attributes[:male],
        search_attributes[:female]
      ])
    end
  end

end
brntsllvn
  • 931
  • 11
  • 18