Has_many, find_all problem


#1

ruby 1.8.5, Rails 1.2.1
Caution - I’m a ruby noob.

I have 2 models - Meeting and Meeting_Items.
As you would expect a meeting has_many :meeting_items and a
meeting_item belongs_to :meeting.

When trying to use find_all to return an array which only includes
“agenda items” I found that it always returned the full array of
meeting_items.
To try to find the fault I have reduced the problem to its’ simplest
form that still gives me the problem.

@meeting.meeting_items.find_all{ |m| false}

The code above still returns the full array of meeting_items for the
meeting, I would expect it to return an empty array.

When I do the following I get an empty array returned, which is what I
expect.
[1,2,3,4,5].find_all{|x| false}

Any help appreciated.

Reed


#2

On 2/19/07, reed removed_email_address@domain.invalid wrote:

“agenda items” I found that it always returned the full array of
meeting_items.
To try to find the fault I have reduced the problem to its’ simplest
form that still gives me the problem.

@meeting.meeting_items.find_all{ |m| false}

The find_all is an Array method but meeting_items is not strictly an
array
even though it behaves a bit like one. The find all on a collection of
AR
models is a depricated method. Intead you should use find(:all,
:conditions => … )

The code above still returns the full array of meeting_items for the

meeting, I would expect it to return an empty array.

When I do the following I get an empty array returned, which is what I
expect.
[1,2,3,4,5].find_all{|x| false}

Any help appreciated.

Reed

I think there are a couple of ways to achive this functionality i think
you’re looking for…

Using
Meeting.find(:all, :conditions => { :field => ‘value’ } )

Or you can set this up in the meeting class as a has_many

class Meeting < AR::B
has_many :meeting_items
has_many :agenda_items, :class_name => ‘meeting_item’, :conditions =>
“field=‘value’”
end

then call this by
@meeting.agenda_items

I hope this helps.


#3

Wow, thanks for the info.

has_many :agenda_items, :class_name => ‘meeting_item’, :conditions =>

… is exactly what I am after but I was implementing it in a lame
manner, when compared to this solution.

Cheers,
Reed


#4

another thing you might want to look into is using association
extensions

has_many :items, :class_name => ‘meeting_item’ do
def agendas
find(:all, :conditions => …)
end

def some_other_type
find(:all, :conditions => …)
end
end

what’s nice about this is you can now say

all meeting items

meeting.items

all agenda meeting items

meeting.items.agendas

all ‘some_other_type’ items

meeting.items.some_other_type