开发者

Unable to read values from object returned from ActiveRecord.find

开发者 https://www.devze.com 2022-12-25 01:14 出处:网络
I make the following call to the DB. @patientRegistration = PatientRegistration.find(:all, :conditions=>[\"name = \'#{patientName}\'\"])

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 in开发者_JAVA百科valid values.

Thanks


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消