The code below errors out (undefined method `org_id’ for nil:NilClass). When the query runs in my controller, there is no record in the DB that meets the conditions (I made sure of that), but an ActiveRecord object is still returned.
How can I save code/time and ensure that an object isn’t returned if the conditions aren’t met? Thanks for your time and assistance,
org_role = OrgRole.where("user_id = ? AND role_id = ?", current_user.id, 2)
if org_role
logger.debug "***"
logger.debug org_role[0].org_id #errors here
logger.debug "***"
else
logger.debug "***"
logger.debug "NOTHING FOUND"
logger.debug "***"
end
ActiveRecord::Relation.where returns an array of objects (representing the rows that matched where clause of the underlying SQL statement).
The check
if org_roleshould probably beif org_role.firstorif not org_role.empty?