How to avoid a 'frozen hash' error in Rails without using an empty begin-rescue-end loop?
I have the following method which is called via Ajax:
def decrement
@cart = current_car开发者_C百科t
@line_item = LineItem.find(params[:id])
@line_item.quantity -= 1
if @line_item.quantity == 0
@line_item.destroy
end
begin @line_item.update_attributes(params[:line_item])
rescue
end
respond_to do |format|
format.js {@current_item = @line_item}
end
end
Originally, I had @line_item.update_attributes(params[:line_item]) in an if statement but that would return a "frozen hash" runtime error instead of merely returning false. I think that my begin-rescue-end loop is absolutely ridiculous, though it works, and I am here to ask the proper way to handle this situation in Rails.
Doing a blind rescue
and then discarding the exception is really not the way to go about solving problems. Anything could be going wrong in there and you're ignoring it which is an extremely dangerous practice.
I think part of the problem here is you're potentially destroying a record and then modifying it after it has been destroyed, which is an invalid operation. You may want to specify this a different way:
if @line_item.quantity > 0
@line_item.update_attributes(params[:line_item])
else
@line_item.destroy
end
If you're still having "frozen hash" errors, you probably need to investigate what's being frozen and why instead of simply disregarding the error and continuing on as if nothing's the matter.
You may want to use update_attributes!
and rescue from ActiveRecord::RecordInvalid if there's something that will preclude this from being saved properly. Right now you're ignoring the result of update_attributes
, successful or not.
精彩评论