19 August 2009

Showing success/failure message for CRUD in rails

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:


def create
@is_success = false
@build = Build.new(params[:build])
@is_success = true
rescue Exception=>ex
@message = "Build cannot be saved because #{ex.message} "

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. :-)

def update
@build = Build.find(params[:id])
@is_success = @build.update_attributes!(params[:build])

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

def destroy
@is_success = false
@build = Build.find(params[:id])
@is_success = @build.frozen?

That's it! Simple!! Happy coding :-)