Showing success/failure message for CRUD in rails

August 19, 2009
Fuad

How do you know whether a CRUD is successful in rails?How do you show an user friendly error message based on different error? Here is a brief description:

[sourcecode language=”ruby”] #create

def create
@is_success = false
@build = Build.new(params[:build])
begin
@build.save!
@is_success = true
rescue Exception=>ex
@message = “Build cannot be saved because #{ex.message} ”
end
end
[/sourcecode]

Now from view based on the value of @is_success you can deliver user friendly message. What in case of update? The code will look somehow different. 🙂
[sourcecode language=”ruby”] def update
@build = Build.find(params[:id])
@is_success = @build.update_attributes!(params[:build])
end
[/sourcecode]

Now comes destroy!
If the destroy() is successful then the frozen method will return true! That is how you can be sure whether an object is deleted!

[sourcecode language=”ruby”] def destroy
@is_success = false
@build = Build.find(params[:id])
@build.destroy()
@is_success = @build.frozen?
end
[/sourcecode] That’s it! Simple!! Happy coding 🙂

Contributor: Fuad Bin Omar, COO, Nascenia

Tags: Crud, Rails,

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.