Reputation: 1999
A typical pattern I see in rails controllers for JSON APIs
success = @my_object.save
if success
render @my_object, serializer: SomeSerializer
else
my_custom_error_reporting_method @my_object
end
But this gets extremely repetitive. Is there a known good-practice approach for drying this up?
I was thinking of having
def my_error_handling_render_method(target_object, options)
if target_object.errors.empty?
render target_object, options
else
my_custom_validation_error_raising_method target_object
end
end
This would allow controllers to just do
@my_object.save
my_error_handling_render_method @my_object, serializer: SomeSerializer
This seems reasonable to me but I don't see this pattern around much. It makes me think there's something important I'm not seeing.
Upvotes: 0
Views: 89
Reputation: 467
I have had success with using save!
and create!
, which will raise exceptions if something goes wrong, and rescue_from
in ApplicationController
to catch those exceptions and render something.
Something like this:
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordInvalid, with: ->(error) do
# render something
end
end
class UsersController < ApplicationController
def create
@user = User.new(user_params)
@user.save!
render @user, serializer: UserSerializer
end
end
Upvotes: 2