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:


#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


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])
end


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])
@build.destroy()
@is_success = @build.frozen?
end

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

No comments: