Forum: Ruby on Rails Trying to replace some .find calls with better code

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.
E4655b2aa2768140847acf487dc2b03c?d=identicon&s=25 Tony Tony (slythic)
on 2008-10-14 15:16
Hi all,

This forum has been very helpful in the past so I figured I'd try and
ask for some help on some (yet again) rather "newbie" stuff again.

I currently have the following DB Schema (Two Tables Listed here):

Users Table    (user has_many children)

Children Table (children belongs_to user)
is_lost (boolean)

Users Controller show method:

def show
  @user = User.find_by_login(params[:id])

  @lost_children = @user.children.find(:all, :conditions => "is_lost =


This WORKS. However, I'm sure I can cut down doing a find query by doing
something like this:

@lost_children = @user.children(:is_lost => true)

The above doesn't work for me (as I just made it up out of the blue).
But there must be something of this nature that can aid in avoiding
making another DB call. I've tried searching for a while now but have
had little luck.

At the very least, any suggestions on how to make that code

Many thanks in advance!


P.S. Please let me know if you need more code or explanations.
9b8d00f99fe595bdc45fd30439cf9c8f?d=identicon&s=25 Franz Strebel (Guest)
on 2008-10-14 15:34
(Received via mailing list)
How about looking into named_scope.

in your Child model:

named_scope :lost,
                     :conditions => "is_lost = 't'"

You can then do this:

@user = User.find_by_login(params[:id])
@lost_children = @user.children.lost

9b8d00f99fe595bdc45fd30439cf9c8f?d=identicon&s=25 Franz Strebel (Guest)
on 2008-10-14 15:36
(Received via mailing list)
Forgot to mention that named_scope is native Rails 2.1 or

If you're using an earlier version, you'll need to install the
has_finder plugin.
D6434aa0b7b350f8c3ed0119d81b2ead?d=identicon&s=25 Roy Pardee (rpardee)
on 2008-10-14 15:41
(Received via mailing list)

  @lost_children = {|c| c.is_lost}

This topic is locked and can not be replied to.