In this case you should use 2 finds. One to find the records and one
to find all associated records. On the associated records array you
can do a find { |record| record.associated_id == actual.id} this is
the same effect as eager loading. I dont know if a lambda would work
on the association, though.
2009/10/29, dino d.
<dinodorroco-/E1597aS9LQAvxtiuMwx3w@public.gmane.org>:>
> 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
>
>
>
> >
>
--
Von meinen Mobilgerät aus gesendet