Join model between three models, has_many :through with parameters (add join condition)

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs