加入过滤表中的has_many:通过回报率
-
24-09-2019 - |
题
我有以下模型,其中我经由使用滑轨的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
我想找个英语语言翻译为特定的产品。
我可以列出相关联的语言和翻译:
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'])
这最后一位应当产生相同的SQL查询,在加入与语言翻译,然后通过它的LANG_CODE滤波。
其他提示
Yaraher的答案的作品,但我发现完成同样的事情更简单的方法:
t = Translation.find(:first,
:conditions => { :product_id => prod.id,
:language_id => lang.id })
不隶属于 StackOverflow