Forum: Ruby on Rails find_all on an array of ActiveRecords

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
1a18b4d281ba02cc09f6ba9c67e61f6f?d=identicon&s=25 Dave Roberts (Guest)
on 2007-07-20 12:45
(Received via mailing list)
In my project, an account has_many entries and an entry
has_and_belongs_to_many tags.
I want to find all of the entries for an account which are tagged with
"some specific tag"

The code which I thought would do this is:
@entries = @account.entries.find_all{|entry|entry.tags.collect{|tag|}.include?(}

However, this returns an array containing all entries for the account,
and ignores the include? condition.

While attempting to debug the problem, I simplified the expression:

@entries = @account.entries.find_all{|entry|false}

This too returns an array containing all entries for the account.
@account.entries.class is an Array, so I assume the find_all which I
am calling is Enum#find_all and not ActiveRecord#find_all (whic have
much different functionality!)

Can anybody point out where I am wrong?
4765b690d8d04b089b0a7b0ee7768ebc?d=identicon&s=25 Stijn Pint (spint)
on 2007-07-20 13:02
I think this should do it:

@entries = @account.entries.find(:all, :include => :tags, :conditions =>
[" = ?",])

D7c511ce5025d37b8c6bd9134e0f2bd9?d=identicon&s=25 Thorsten (Guest)
on 2007-07-20 13:09
(Received via mailing list)
I think it indeed IS the ActiveRecord#find_all Method, for the
following reason:

if you call the find_all method directly on the association like:
without the entries being eager-loaded before, it does an AR#find_all
because @account.entries doesn't hold any objects yet.
This would also explain why the block isn't evaluated: AR#find_all
doesn't take a block.

Rails aliases Enumerable#find with #detect, and #find_all with

@entries ={|entry|entry.tags.collect{|tag|}.include?(}

this would also work:
@entries = @account.entries.to_a.find_all{|entry|entry.tags.collect{|

or, use AR for the whole operation:
@entries = @account.entries.find(:all, :include => :tags, :conditions
=> [" = ?",])

Less code, less records fetched by SQL ...
1a18b4d281ba02cc09f6ba9c67e61f6f?d=identicon&s=25 Dave Roberts (Guest)
on 2007-07-20 13:16
(Received via mailing list)
Thank you both, this is very helpful
This topic is locked and can not be replied to.