Heres a short snippet that I created. I wanted to make sure that the record existed, and it actually belonged to the user before trying to delete it.
for delEmp in employ @Count = ListCrew.count(:all, :conditions => [" saved_by = ? AND employee_ID = ? ", session[:employee_id], delEmp.to_i]) if @Count > 0 crew = ListCrew.find(:first, :conditions => [" saved_by = ? AND employee_ID = ? ", session[:employee_id], delEmp.to_i]) crew.destroy end #if end #for
It seems like there should be a way to do this with a single DB query instead of using 2. Any suggestions?
Maybe this? The find will only return an object if one matches the conditions, and your conditions seem to be the same from count to find, so if we find it, destroy. Wrap it in a begin/rescue/end in case we dont' find it and it complains about that, the rescue will shut it up.
for delEmp in employ begin ListCrew.find(:first, :conditions => ["saved_by = ? AND employee_ID = ?", session[:employee_id], delEmp.to_i]).destroy rescue nil end end