Better way to access individual Rails ActiveRecord error?

时光怂恿深爱的人放手 提交于 2019-12-11 00:16:01

问题


I'm trying to access the type attribute of an ActiveRecord::Error object. The reason I'm doing this is because I want to redirect a user to a different page depending on the type of validation that failed (an attribute can fail validation in several ways, so the attribute itself is insufficient).

The only way I've found that I can do this is:

obj.errors.instance_variable_get(:@errors)["attr"][0].type

which is just plain nasty. Is there a better way?


回答1:


Looks like your best bet is to extend ActiveRecord::Errors.

class ActiveRecord::Errors
  def error_type(attr)
    @errors[attr] && @errors[attr].first.type
  end
end


来源:https://stackoverflow.com/questions/3671098/better-way-to-access-individual-rails-activerecord-error

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