Neigaard
Neigaard

Reputation: 4074

How can I catch validation errors in my controller

I have a model like this:

class Schedules < ActiveRecord::Base
  validates_presence_of :scheduleTime
end

I do not have a view, as my controller only works as a JSON talking webservice, but I would like to "catch" what ever validations errors (there will be more validations in the future) from the model in the controller, and return a error message/code in my JSON response.

How can I do this?

Thank you

Upvotes: 1

Views: 4033

Answers (2)

Neigaard
Neigaard

Reputation: 4074

The schedule.save(false) will ignore all validation errors, and that is not what I want. Here is what I did, is there a better way?

if schedule.save
  render :json => schedule.id
else
  err_json = "err:"
  schedule.errors.each do |attr_name, message|
    if message == "is invalid"#field is invalid
      case attr_name
        when "from"
          err_json  err_json
end

Thank you

Upvotes: 1

aNoble
aNoble

Reputation: 7072

You should be able to do

schedule.save(false)
schedule.errors.full_messages

Upvotes: 0

Related Questions