Can someone suggest a better way to do this?

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?

Why do you need to do the count first? Just do the find, check if it
actually
returns the valid object and delete it only in this case.

On Tuesday 03 October 2006 23:55, Mic wrote:

[" 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?


WBR, Oleg Ivanov
ICQ #69991809
Jabber: [email protected]

[" 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