Consider whether two filters combine as 'and' or 'or'

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the user-input-and-output category.

Last Updated: 2024-11-23

I had user input as part of a search form for finding law tutors. Among other fields (like select boxes for "law level" and "school"), the form had check boxes for skype_available and in_person_available.

The backend code for the search was:

tutors = tutors.where(skype_available: true) if skype_available
tutors = tutors.where(in_person_available: true) if in_person_available

This ended up being incorrect in the case where both boxes (skype_available and in_person_available) were ticked: My desired output here was that tutors with EITHER of these capabilities would be listed - since that matches the user's meaning. But the effect, with the code as I'd written it, was that only tutors who had BOTH capabilities would display — which wasn't really useful at all.

You might characterize this as the difference between OR and AND operations.

Here is a possible rewrite.

if skype_available && in_person_available
  tutors = tutors.where(skype_available: true).or.where(in_person_available: true)
else
  tutors = tutors.where(skype_available: true) if skype_available
  tutors = tutors.where(in_person_available: true) if in_person_available
end