5

I want to order some records of a model that has a relation to another model (with translated attributes). Here an example:

  1. I have a model Project
  2. I have a model Task
  3. I have the relation Project has_many Tasks
  4. The model Task has attribute name globalized (on task_translations table)

Now, I want to order all projects by its tasks name. How can I write this scope? How can I join the translation table in Rails like method with_translation in gem globalize (https://github.com/globalize/globalize/blob/eccb924ac9641b52399f22525b0e3ec004739f4c/lib/globalize/active_record/class_methods.rb) but from related object Project?

> Project.all.joins(:tasks) ... (how to include task translation table) ...
phlegx
  • 2,132
  • 2
  • 29
  • 36

1 Answers1

11

I believe the task_translations is directly related to tasks and you can query it like so:

Project.joins(tasks: :translations)
gabrielhilal
  • 10,285
  • 6
  • 45
  • 74
  • 3
    And this is how you access the table `Project.joins(tasks: :translations).where("task_translations.name = ?", "todo") }` – Epigene Oct 22 '15 at 13:11
  • @Epigene What about different locales? – Talha Shoaib Mar 05 '19 at 12:14
  • 2
    @TalhaShoaib Assuming the locale is a column in `task_translations` table, an additional `.where("task_translations.locale = ?", locale)` should do it. – Epigene Mar 05 '19 at 13:10