# Join model between three models, has\_many :through with parameters (add join condition)

**URL:** <https://www.ruby-forum.com/t/join-model-between-three-models-has-many-through-with-parameters-add-join-condition/143071>\
**Category:** Rails\
**Created:** [July 14, 2008, 11:07pm UTC](https://www.ruby-forum.com/t/join-model-between-three-models-has-many-through-with-parameters-add-join-condition/143071 "2008-07-14T23:07:31Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![eduardo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/6a8cbe/32.png) [@eduardo](https://www.ruby-forum.com/u/eduardo)\
**Post date:** [July 14, 2008, 11:07pm UTC](https://www.ruby-forum.com/t/join-model-between-three-models-has-many-through-with-parameters-add-join-condition/143071/1 "2008-07-14T23:07:31Z")

</div>

I have a join model (context) that ties three models together (files,  
versions, sentences). Sentences have a translation.

translation \<-- sentences  
|  
|  
files----(context)----versions

files-\> has\_many :sentences, :through =\> :contexts  
sentences -\> belongs\_to :translation

I want to get all sentences and their translations for a file for a  
given version. I want to do it with eager loading, to feed the view  
with the whole set and not have additional queries.

If I do file.sentences.find(:all,:include =\> :translation) I get all of  
them (for all versions). If I add conditions, say ‘version\_id = 2’,  
then they applied to all records, not to the join and I lose the  
untranslated sentences.

I’ve made it work by adding at runtime, right before the .find(), a  
has\_many relationship, like this:

Files.has\_many “sentences\_by\_version\_#{vid}”.to\_sym,:class\_name =\>  
‘Context’,:conditions =\> [‘contexts.versio\_id = ?’,vid]

And then including :sentences\_by\_version\_2 (or whatever id’s value is).

Is there a cleaner way to do this with eager loading? The has\_many has  
to be created everytime. Maybe overloading a method of my class and  
using a lambda? Any ideas?

I need to get the sentences (with outer join), not the contexts, because  
that yields the sentences that are not translated. So, somehow I need  
to push a condition on the join.

Thanks, Eduardo.
