フィルタリングはhas_manyの中でテーブルを結合する:RoRので通過

StackOverflow https://stackoverflow.com/questions/2171098

  •  24-09-2019
  •  | 
  •  

質問

:パラダイムを通じて:

私はRailsのにhas_manyを使用して、変換テーブルを経由して言語や製品テーブルに参加した次のモデルを持っています

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関連する言語と翻訳を一覧表示することができます:

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

役に立ちましたか?

解決

あなたはこれに沿って何かを必要があると思います:

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'])

最後のビットがそれのLANG_CODEによるフィルタリング[言語と翻訳に参加すると、同じSQLクエリを生成する必要があります。

他のヒント

はYaraherの答えは動作しますが、私は同じことを達成するために簡単な方法を見つけましたが、

t = Translation.find(:first, 
                     :conditions => { :product_id => prod.id, 
                                      :language_id => lang.id })
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top