Reputation: 1356
I was working on asp.net mvc before, now i am working on Ruby on Rails.
in asp.net mvc we use to handle validation using action filters, i am wondering if same thing is available in rails too.
i want to create custom validation class to handle business validation, so that action filter can process the exception based on the type of exception it is.
Upvotes: 1
Views: 422
Reputation: 2638
I'm not at all familiar with asp.net, and may be misunderstanding your question but here is a way to handle exceptions that might occur when in an action of a Controller.
A generic Controller with some actions:
class SomethingController < ApplicationController
def show
@user = User.find_by_id(params[:user_id])
end
end
Notice that the SomethingController is inheriting from this ApplicationController:
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound do |exception|
return render :json => {:status => 'error', :message => "given id does
not correlate to a record", :code => 404}
end
end
Because the SomethingController
(along with most other controllers) inherit from ApplicationController
most exception handlers can be placed in ApplicationController
.
Now the actual exception is not generated in the controller, but rather comes from a model. In the example above, and assuming I only have 10 users, ActiveRecord::RecordNotFound
is an exception that will be called when the User
model calls the find_by_id
method with parameter 1000. There is no user with id 1000, so an ActiveRecord::RecordNotFound
exception will be returned to the calling controller. SomethingController
doesn't know how to handle this action, and will thus refer to its parent which has an appropriate handler.
Upvotes: 3