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.
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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.