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

Published On: August 19th, 2009 / Categories: Blog, Ruby on Rails, Technology / Tags: , /