If I have an association

A habtm B

and I say A.find.., :include => B

but I only want some of the B's to be loaded, the rails docs (http://
ar.rubyonrails.org/classes/ActiveRecord/Associations/
ClassMethods.html) say:

If you do want eagerload only some members of an association it is
usually more natural to :include an association which has conditions
defined on it:

  class Post < ActiveRecord::Base
    has_many :approved_comments, :class_name => 'Comment', :conditions
=> ['approved = ?', true]
  end

  Post.find(:all, :include => :approved_comments)

Which is fine if you know ahead of time what the conditions are.  If
you only know the condition at the time of the request, things get
trickier. For example, if B has a user_id field, and you only want to
show this user's B's.

One solution I came up with was to create a cattr_accessor in A and
set it upon login, and then use that in the association, as the docs
suggest.

cattr :current_user
...
has_one :users_b, :class_name => 'B', :conditions => "user_id = #
{current_user.id}"

This works fine, but it fails miserably when class caching is enabled
(in production).  And I'd much rather send user_id as a parameter, and
use that param in a find.

So, is there any way to have conditional eager loading with dynamic
conditions?

Note, :conditions does not work because those conditions are applied
to the entire join, not just the left joined table (this is verified
in the docs, same link as above).

Thanks for any help,
Dino



--~--~---------~--~----~------------~-------~--~----~
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 [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to