Connection table filtering in has_many: through RoR

I have the following models in which I join the Language and Products table through the Translation table using Rails has_many: through the paradigm:

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 want to find an English translation for a specific product.

I can list related languages ​​and translations:

 prod = Product.find(4) en = Language.find(:first, :conditions => { :lang_code => 'en' }) puts prod.translations puts prod.languages 

Fingerprints:

 #<Translation:0x11022a4> #<Translation:0x1102114> #<Language:0x602070> #<Language:0x602020> 

(English and French translation is used for this product.)

How can I get a translation for prod that matches the en language?

If that doesn't make sense, here is the equivalent 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
source share
2 answers

You will need something like this:

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

The "Translations with languages" connection will appear in the code and your lang_code will be accordingly filtered accordingly.

If the brackets confuse you a little (sometimes I know), you can also do something like this:

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

This last bit should produce the same SQL query, joining Translations with Language and then filtering it with lang_code.

+3
source

The answer to Yaraher works, although I found an easier way to accomplish the same thing:

 t = Translation.find(:first, :conditions => { :product_id => prod.id, :language_id => lang.id }) 
0
source

Source: https://habr.com/ru/post/1299867/


All Articles