How to show if there are children in a list?

Larry Kelly wrote:

I have the following parent - child models.

class Parent   has_many :children end

class Child   belongs_to :parent, :foreign_key => "parent_id" end

Now, in my list of parents, the user can click a link to see the children for a parent. What I'd want to do is to show whether a parent has any children on the parent list page, without the user having to click on the link to find out.

My current query to populate the table is as follows:

@parents = Parent.find(:all, :order => "name")

Can this query be modified to get the number of children as well? Or, return true if the parent has at least one child?

You can use Rails' automatic association size caching by adding a children_count field to the parents table, then testing whether parent.children_count == 0.

Otherwise you'd have to add :joins, :group, and :select options to your find call to add a attribute to each parent instance that reflects the number of or presence of children.