Pattern for translating ActiveRecord validation errors to API responses

廉价感情. 提交于 2019-12-11 01:19:15

问题


I have a Rails 2.x app that I'm building a RESTful interface for.

For some (good) reason, I've chosen to expose some of the fields on my ActiveRecord models through the API using different names than the underlying fields in MySQL.

For example, a lot of my MySQL field were prefixed with the model name (user_type, user_first_name, etc.). My request/responses use the names without prefixes (type, first_name).

The action methods look like (and yes, this is already a source of pain for maintenance)

def create 
  u = User.new
  u.user_type = params[:type]
  u.user_first_name = params[:first_name]
  u.save!
end

My problem comes when rescuing ActiveRecord::RecordInvalid. I translate the errors collection on the record into a key that the client app can make some sense of. For example:

validation_error.blank.user_first_name

via:

rescue_from ValidationError, ActiveRecord::RecordInvalid do |e|
  errors = []
  e.record.errors.each_error do |attr, error|
    errors << {:key => "validation_error.#{error.type.to_s}.#{attr}"}
  end
  errors.uniq!
  respond_to do |format|
    format.xml { render_xml_error errors, :unprocessable_entity}
  end
end

The problem is that the "user_first_name" wasn't a field that the client code knows anything about -- yes, you can figure it out because you're a human, but it doesn't match any of the fields that were passed in exactly

So, the more general question is: how can I maintain this type of incongruous mapping between my public API facade and the underlying SQL model without doing hand-to-hand combat with every action method and error rescue translating the field names?

Would switching to Rails 3 help me in this specific regard?

One idea suggested was maintaining a separate I18n localization file (en.yml) for the API resources so that I can map the field names -- but that still feels heavy and fragile

来源:https://stackoverflow.com/questions/8933864/pattern-for-translating-activerecord-validation-errors-to-api-responses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!