4

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';

4

2 に答える 2

3

これに沿って何かが必要になります:

product = Product.find(4)
translation = product.translations.find(:first,:joins=>:languages, :conditions=>{:language=>{:lang_code=>'en'}})

このコードは、翻訳と言語の結合を生成し、それに応じてlang_codeをフィルタリングします。

角かっこが少し混乱する場合(私は時々そうすることを知っています)、次のようなこともできます:

translation = product.translations.find(:first,:joins=>:languages, :conditions=>["languages.lang_code like ?",'en'])

その最後のビットは、同じSQLクエリを生成し、TranslationsとLanguageを結合してから、そのlang_codeでフィルタリングする必要があります。

于 2010-01-31T19:34:32.680 に答える
0

Yaraherの答えは機能しますが、同じことを達成するためのより簡単な方法を見つけました。

t = Translation.find(:first, 
                     :conditions => { :product_id => prod.id, 
                                      :language_id => lang.id })
于 2010-01-31T19:53:18.663 に答える