Error handling in Rails Controller for adding embedded Mongoid documents to Model
Posted
by
Dragonfly
on Stack Overflow
See other posts from Stack Overflow
or by Dragonfly
Published on 2012-09-27T15:37:49Z
Indexed on
2012/09/28
15:38 UTC
Read the original article
Hit count: 538
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!
© Stack Overflow or respective owner