Problem with ActiveRecord and Associations

Hi,

I’m having what I believe to be a typecast problem with ActiveRecord and
Associations. In the code below, I need to flag a contact record for
deletion if the contact doesn’t have any addresses or books records:

sql = “select id, delete_flag from contacts where id = #{params[:id]}”
contact = Contact.find_by_sql(sql)
if (contact[0].addresses.count + contact[0].books) > 0
#contact = Contact.find_by_sql(sql)
contact[0].update_attribute(:delete_flag,‘true’)
end

The if statement is correctly getting the correct count of
children/detail recs, but the contact[0].update_attributes() is failing
with the following ugly error:

SyntaxError ((eval):1:in compute_type': compile error (eval):1: parse error, unexpected tINTEGER Object::0 ^): c:/Ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:1244:incompute_type’
c:/Ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:983:in
instantiate_without_callbacks' c:/Ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/callbacks.rb:215:ininstantiate’
c:/Ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:390:in
`find_by_sql’

If I uncomment out the line above containing the 2nd find_by_sql,
everything works. It seems that referencing
contact[0].addresses.count and contact[0].books is changing the type of
the contact var.

Any suggestions?

Oops,

if (contact[0].addresses.count + contact[0].books) > 0

should be

if (contact[0].addresses.count + contact[0].books.count) > 0

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Peter J. wrote:

contact[0].update_attribute(:delete_flag,'true')
c:/Ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:1244:in

contact[0].addresses.count and contact[0].books is changing the type of
the contact var.

The intentions in your code should be nicer…

contact = Contact.find( :first, :select=>“id, delete_flag”,
:conditions=>[ “id=:id”, params ] )

then do everything with “contact” not “contact[0]”. Also “contact” is a
horrible name for an array of results. If you truly want
an array use “contacts” since it more clearly shows the intent of your
code.

Zach
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFFgZ8ZMyx0fW1d8G0RAgV2AJ0S+Aq3Row4wQy2C/EB17VUGpVWiACfeeXh
VCCRgU1Lo/Jkn/w7+YUj1H8=
=uson
-----END PGP SIGNATURE-----

Zack,

Thanks for responding. Unfortunately, it doesn’t work - it’s clear now
that the .count in the IF statements is running a query and assigning
the result back to the contact var, thus causing the error because the
original contents of the contact var are now gone.

Thanks for the tip on ‘contact’ vs. ‘contacts’. However, as I’m pulling
the record by :id, there’s only going to be 1 record/contact fetched.