Eduardo
2008-Jul-14  20:24 UTC
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.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---