Rails where in fields of join table

I have a select with joins in tree tables

.joins(module_table_1: [module_table_2: :module_table_2_type])

And I'd like to use where syntax of Active Record like this:

result = Module::Table_1
  .joins(module_table_1: [module_table_2: :module_table_2_type])
  .where(number: 6)
  .where(module_table_2_type: {cdg_type: [1012, 77]})

If I do this my where is composed with module name like this:

module_table_2_type.cdg_type in (1012,77)

that is not corret, the correct is:

table_2_type.cdg_type in (1012,77)

I know I can do this .where('table_2_type.cdg_type in (1012,77)'), with string only syntax but I want active record way to do this correctly.

Any idea?

Upvotes: 2

Views: 591

Answers (1)

Helio Borges
Helio Borges

Reputation: 122

These are not elegant ways to solve your problem. I'm sure there are better ways, but give it a try:

result = Module::Table_1
.joins("INNER JOIN table2 on table1.table2_id = table2.id INNER JOIN table2_type on table2.id = table2_type.table2_id" )
.where(number: 6)
.where(table_2_type: {cdg_type: [1012, 77]})

Upvotes: 1

Related Questions