-1

I'm sure this will be simple for someone who knows what they are doing. I want to write this statement as a scope - and I'd rather use Arel format but can't work out the OR inside the AND

select * from contacts where contact_type in (1,2) and 
((contactable_type = 'Developer' and contactable_id = 10) or (contactable_type = 'Development' and contactable_id = 24))

so to start my scope - the first bit is simple

scope :of_type,
        lambda { |types|
            where(contact_type: types)
        }

but it is the AND with nested ORs that I cannot get. I will obviously send in the ids I need

scope :of_type,
        lambda { |types, developer_id, development_id |
            where(contact_type: types) .. .
        }
user1587804
  • 121
  • 1
  • 7

1 Answers1

0

Maybe you wanted something like this:

class Contact < ApplicationRecord
   scope :contact_type_eq, lambda { |contact_type| 
     where(contact_type: contact_type) 
   }

   scope :shaitan_eq, lambda { |shaitan|
     where(
       shaitan_type: shaitan.class.to_s, 
       shaitan_id: shaitan.id
     )
   }

   scope :shaitan_colect_with_type, lambda { |shaitans, types|
     main_scope = contact_type_eq(types)
     scope = main_scope.shaitan_eq(shaitans.first)
     shaitans[1..-1].each do |shaitan|
       scope = scope.or(main_scope.shaitan_eq(shaitan))
     end
     scope
   }
end

you can use it as:

Contact.shaitan_colect_with_type([developer, development], [1,2])

or

Contact.contact_type_eq([1,2])
       .shaitan_eq(developer)
       .or(
          Contact.contact_type_eq([1,2])
                 .shaitan_eq(development)
        )
Viktor Ivliiev
  • 1,015
  • 4
  • 14
  • 21