Error handling in Rails Controller for adding embedded Mongoid documents to Model
- by Dragonfly
I have a Item model that has embedded documents. Currently, the following comments_controller code will add a comment to the item successfully. However, if pushing the comment document onto the comments array on item fails, I will not know this.
#this does work, but i do not know if the push fails
def create
comment = Comment.new(:text => params[:text])
@item.comments << comment
render :text => comment
end
I would like to have something like this, but @item.comments << comment does not return true or false:
#this does not work
def create
comment = Comment.new(:text => params[:text])
if @item.comments << comment
render :text => comment
else
render :text => 'oh no'
end
end
Nor does it throw an exception when the document push fails:
#this does not work
def create
begin
comment = Comment.new(:text => params[:text])
@item.comments << comment
render :text => comment
rescue Exception => e
render :text => 'oh no'
end
end
Thanks!