Rails has_many:throughパラダイムを使用してTranslationテーブルを介してLanguageandProductsテーブルに結合する次のモデルがあります。
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';