我有以下模型,在这些模型中,我使用 Rails has_many :through 范式通过 Translation 表加入 Language 和 Products 表:
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
我想查找特定产品的英语翻译。
我可以列出相关的语言和翻译:
prod = Product.find(4)
en = Language.find(:first, :conditions => { :lang_code => 'en' })
puts prod.translations
puts prod.languages
这打印:
#<Translation:0x11022a4>
#<Translation:0x1102114>
#<Language:0x602070>
#<Language:0x602020>
(此产品有英文和法文翻译。)
如何获得与语言prod
对应的翻译en
?
如果这没有意义,这里是等效的 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';