What is the new way to check if a parent has child items? In rails
1.2.6 I did this:
if @client.has_line_items?
Client being the parent and line_items the children.
Now that I have upgraded to rails 2.0.1 (on my way to current
) I
am getting this message:
undefined method `has_line_items?' for #<Client:0x7f3b093b01a0>
How should I format the query now?
Regards,
Paul Thompson
Paul,
if @client.line_items.exists?
Anthony Crumley
http://commonthread.com
Thanks Anthony,
It's better, but I'm not quite there yet. I am now getting:
wrong number of arguments (0 for 1)
Regards,
Paul Thompson
Paul,
Sorry, but I gave you the wrong method. It should have been …
unless @client.line_items.empty?
Anthony Crumley
http://commonthread.com
Thanks Anthony,
Did a little more homework and decided to use:
unless @client.line_items.blank?
as .blank? will not bomb on a nil condition and .empty? will.
But thanks very much for pointing me in the right direction.
Regards,
Paul Thompson
Not sure why you'd want to do that - if a has_many is returning nil
(rather than an empty array) something has gone terribly, terribly
wrong. Also, .blank? isn't proxied like .empty? is - blank? will load
the association then call the method; empty? is defined in
AssociationCollection to do a direct SQL query if the association
isn't loaded, potentially skipping a bunch of unneeded object
creation.
Certainly not a big deal, but worth following the standard API for
efficiency's sake.
--Matt Jones