Search code examples
ruby-on-railsrubyruby-on-rails-5acts-as-taggable-on

acts_as_taggable_on multiple fields query using an OR


So i’m trying to write a query to fetch users based on the skills they have, the implementation goes like this :

A user has primary and secondary skills, both using acts_as_taggable_on

this is the scope i’ve got now

scope :by_skills, (lambda do |primary, secondary|
  if primary.present? && secondary.present?
    tagged_with(primary, on: :primary_skills, any: true)
      .tagged_with(secondary, on: :secondary_skills, any: true)
  elsif primary.present?
    tagged_with(primary, on: :primary_skills, any: true)
  elsif secondary.present?
    tagged_with(secondary, on: :secondary_skills, any: true)
  end
end)

problem with this now is that if both primary & secondary is present, the query fired would be an AND i.e primary and secondary, I’d like it to be an OR, and in no way am i able to figure that out


Solution

  • Try or introduced in Rails 5.

    scope :by_skills, (lambda do |primary, secondary|
      if primary.present? && secondary.present?
        tagged_with(primary, on: :primary_skills, any: true).or(
          tagged_with(secondary, on: :secondary_skills, any: true))
      elsif primary.present?
        tagged_with(primary, on: :primary_skills, any: true)
      elsif secondary.present?
        tagged_with(secondary, on: :secondary_skills, any: true)
      end
    end)