Forum: Ruby on Rails Conditionalizing find via has_many

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Duane M. (Guest)
on 2007-06-28 23:00
I have a has_many relationship (person has_many meetings).  The majority
of people in my system have no meetings, so I only want to deal with
Person where meetings.size > 0.  Is there a simple and elegant way to
manipulate the find() method I'd normally use, possibly via :include and
:conditions, so that I can use this as needed without having to resort
to SQL?   I get the concept of Person.find(:include=>['meetings']) to
hook the two up and make meetings accessible, but :conditions deals with
a direct SQL statement and not a Ruby statement, doesn't it?

It would be even better if I could do something equivalent to
redefining find(:all) so that this only ever deals with that particular
condition.
George GSGD (Guest)
on 2008-02-27 16:03
(Received via mailing list)
Hi Duane,

Did you manage to solve this, I've got a similar problem now that I'm
trying to work out

Thanks,
George.

On Jun 28 2007, 7:00 pm, Duane M. <rails-mailing-l...@andreas-
Ilan B. (Guest)
on 2008-02-27 17:33
Duane M. wrote:

>
> It would be even better if I could do something equivalent to
> redefining find(:all) so that this only ever deals with that particular
> condition.

As far as I know, there is no AR mechanism to use pure ruby syntax to
perform a search through a relation whether that is has_many,
belongs_to, etc..

However, this may be close to what you are looking for:

class Person < ActiveRecord::Base
  def self.with_meeting_scope
    with_scope(:find => {:joins => "meetings on meetings.person_id =
people.id"}) {yield}
  end

  def self.find_all_with_meetings
    with_meeting_scope {find :all}
  end
end

I myself however would just use the sql as I find that the with_scope
syntax can quickly get out of hand and it usually turns out to be vendor
specific anyways..

hth

ilan
This topic is locked and can not be replied to.