maxhungry
maxhungry

Reputation: 1922

globalize3 - Query translated attribute

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?

Upvotes: 0

Views: 68

Answers (1)

dleve123
dleve123

Reputation: 100

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!

Upvotes: 0

Related Questions