0

I'm attempting to do a JOIN on two tables, using a partially constant value and a second constraint.

I have two models, car and driver. They both have a column name. The association is formed as such: A car has many drivers. The driver's name is the same as the car, appended with '_driver', limited to drivers whose hair is brown.

Example:

  • A car has the name quick
  • Its drivers have the name quick_driver, and have hair_color brown.

Following this post https://stackoverflow.com/a/20412163/1025846, here is my attempt with has_many:

has_many :drivers, -> (object) { 
                     where('name LIKE self.name%').
                     where("name LIKE %'?'", '_driver').
                     where(hair_color: 'brown') 
                   },
                   class_name: 'Animal::Driver'

This isn't working, and I'm at a loss of how to continue.

For simplification, I don't believe my issues have to do with the hair_color, so I believe this can be ignored.

ardavis
  • 9,842
  • 12
  • 58
  • 112
Josh Johnson
  • 563
  • 3
  • 11
  • 29

1 Answers1

0

Perhaps try something like:

has_many :drivers, -> (object){ 
    where("name LIKE '?'", object.name).
    where("name LIKE '?'", "#{object.name}_driver").
    where(hair_color: 'brown') }, 
  :class_name => 'Animal::Driver'

Note: bug-testing is left as an exercise to the reader ;) this code is to show you the kind of thing you might be able to try

Taryn East
  • 27,486
  • 9
  • 86
  • 108
  • It's still not generating the SQL correctly. It seems to still be querying on the `driver.car_id`, adding the where clause for name and hair_color. – Josh Johnson Apr 03 '18 at 13:07
  • 1
    Here's the sql being generated, using only the middle 'where' from your example: `SELECT "drivers".* FROM "drivers" WHERE "drivers"."car_id" = $1 AND (name LIKE ''quick_driver'') [["car_id", 1]]` – Josh Johnson Apr 03 '18 at 13:11
  • Can you show me the SQL you'd like it to be, and perhaps we can work backward from that? (add it to your question rather than the comments as the formatting is hard to read)? – Taryn East Apr 04 '18 at 23:35