lundi 1 juillet 2019

joins on tables without relation in rails

What's the work around of not being able to use joins on tables that don't have relation?

E.g:

class Student
end

class Lesson
end


There is no explicit correlation between Student and Lesson, however, in DB, we have implicit correlation: students.lesson_id and lessons.id.

Using pure SQL can join these two tables, however, using joins provided by rails like this:

Student.joins(:lesson).where('student.lesson_id=lesson.id')

will throw "Association named 'lesson' was not found on Student; perhaps you misspelled it?"

I'm looking for work around with below requirements:

  • In order to improve the efficiency, using RDBMS queries will be ideal. (Rails sort_by, find etc are not)
  • In order to improve readability, raw SQL is not ideal.

Is there any work around out there? Thanks!

Aucun commentaire:

Enregistrer un commentaire