views:

23

answers:

1

I make the following call to the DB.

@patientRegistration = PatientRegistration.find(:all, 
                         :conditions=>["name = '#{patientName}'"])

This searches for a patient registration based on a given name. I get a valid @patientRegistration object. When I invoke @patientRegistration.inspect it prints correctly all the values for the object in the DB.

But when I try to read a particular attribute (say id or name) by doing the following: @patientRegistration.id or @patientRegistration.name, I get invalid values. Either its blank or some junk values. I don't understand how inspect is able to retrieve all the values correctly but reading individual attributes gives invalid values.

Thanks

+3  A: 

find(:all) returns an array of all the records that match the conditions (inspect probably shows you the result in square brackets). @patientRegistration.first.name will return you the name of the first record in the array. However, if you are only interested in the first or only record that matches the conditions, then you can use find(:first) instead:

@patientRegistration = PatientRegistration.find(:first, 
                         :conditions => ["name = ?", patientName])

Note that I've also changed your condition to use a parameter so that it is no longer at risk from SQL injection attacks.

You can also re-write this code using an attribute-based finder:

@patientRegistration = PatientRegistration.find_by_name(patientName)

This will do a find(:first). For the equivalent of find(:all), use find_all_by instead of find_by.

Phil Ross
It works. Great!. Thanks
Venki