I have the following models in which I join the Language and Products table via the Translation table using the Rails has_many :through paradigm:
class Language < ActiveRecord::Base
has_many :translations
has_many :products, :through => :translations
end
class Translation < ActiveRecord::Base
belongs_to :product
belongs_to :language
end
class Product < ActiveRecord::Basehas_many :translations
has_many :translations
has_many :languages, :through => :translations
end
I want to find the English Language Translation for a particular Product.
I can list the associated Languages and Translations:
prod = Product.find(4)
en = Language.find(:first, :conditions => { :lang_code => 'en' })
puts prod.translations
puts prod.languages
This prints:
#<Translation:0x11022a4>
#<Translation:0x1102114>
#<Language:0x602070>
#<Language:0x602020>
(There is an English and French translation for this product.)
How can I get the Translation for prod
corresponding to the en
Language?
If that doesn't make sense, here is the equivalent SQL:
SELECT t.* FROM products p, translations t, languages l WHERE l.id = t.language_id AND p.id = t.product_id AND l.lang_code = 'en';