0

I have 2 models:

class Gender < ActiveRecord::Base
  translates :name
  has_many :products
end

class Product < ActiveRecord::Base
  translates :description
  belongs_to :gender 
end

After integrating with globalize3 I cannot figure out how to get query that joins to work, for example: Product.joins(:gender).where(genders: { name: 'male' })

which generates this sql query:

SELECT "products".* FROM "products" 
INNER JOIN "genders" ON "genders"."id" = "products"."gender_id" 
WHERE "genders"."name" = 'male'`

But I think I need a sql query that looks like this?

SELECT * FROM products 
INNER JOIN genders on genders.id = products.gender_id 
INNER JOIN gender_translations on gender_translations.gender_id = genders.id 
WHERE gender_translations.name = 'male';

So how does one do the rails equivalent of this sql query?

maxhungry
  • 1,863
  • 3
  • 20
  • 28

1 Answers1

0

Something along the lines of Product.joins(gender: :translations).where(gender: { translations: { name: 'male' }}) should do the trick I believe.

The joins(gender: :translations) is a nested inner join. So you're joining products-> genders, and genders -> gender_translations.

The where hash syntax is just an attempt to generate the SQL: where("gender_translations.prompt = 'male'"). If the hash syntax isn't correct/fights you, I'd just revert to the raw SQL just mentioned. It's arguably more clear anyways!

dleve123
  • 100
  • 7
  • thank you for your reply @dleve123, but `Product.joins(gender: :translations).where(gender: { translations: { name: 'male' }})` is exactly what I ended up doing when I asked this question, and at the end I did write raw sql in rails where method like you suggested. Perhaps I'll dig out the old error message later and we can have a look from there. – maxhungry Nov 16 '14 at 20:20