2

Admin Model:

has_many :transport_vehicles_as_driver, class_name: "Transport::Vehicle",as: :driver 
has_many :transport_vehicles_as_attendant, class_name: "Transport::Vehicle",as: :attendant 
relation_1 = Admin.where(category: "TRANSPORT").left_outer_joins(:transport_vehicles_as_attendant).where("transport_vehicles.reference_code LIKE ?", "%#{keyword}%").distinct
relation_2 = Admin.where(category: "TRANSPORT").left_outer_joins(:transport_vehicles_as_driver).where("transport_vehicles.reference_code LIKE ?", "%#{keyword}%").distinct

relation_1.or(relation_2) produces the following error:

ArgumentError (Relation passed to #or must be structurally compatible. Incompatible values: [:left_outer_joins])

I have checked the following close stackoverflow sources : Relation passed to #or must be structurally compatible. Incompatible values: [:references]

vamsi
  • 231
  • 2
  • 8
  • What is your desired goal with this query? It seems like you are trying to do `UNION ALL`. Error is trying to tell you, that you cannot use `left_outer_join` with `or` or at least when those two queries have a different value of `left_outer_join`. – edariedl Oct 07 '20 at 18:04
  • 1
    Yes, i'm trying to find the union of two relations.. – vamsi Oct 08 '20 at 05:31
  • 1
    I think you should be able to write it in one query without the union. Only thing it would take is to write custom left join in SQL instead of the "rails" way via association symbols. It could look something like `.joins("LEFT JOIN (transport_vehicles.driver_id = admin.id AND transport_vehicles.driver_type='Admin') OR (transport_vehicles.attendant_id = admin.id AND transport_vehicles.attendant_type='Admin') ")` or something like that I am just guessing the column names. – edariedl Oct 08 '20 at 22:05

1 Answers1

1
Admin.where(category: "TRANSPORT").
  joins("LEFT JOIN transport_vehicles ON
        (transport_vehicles.driver_id = admins.id) OR (transport_vehicles.attendant_id = admins.id)").
  where("transport_vehicles.reference_code LIKE ?", "%#{keyword}%").distinct
Tyler Rick
  • 9,191
  • 6
  • 60
  • 60
vamsi
  • 231
  • 2
  • 8