Martin Gordon
Martin Gordon

Reputation: 36389

Better way to access individual Rails ActiveRecord error?

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?

Upvotes: 2

Views: 922

Answers (1)

wuputah
wuputah

Reputation: 11395

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

Upvotes: 2

Related Questions