开发者

How can I catch validation errors in my controller

I have a model like this:

class Schedules < Active开发者_StackOverflowRecord::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


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


You should be able to do

schedule.save(false)
schedule.errors.full_messages
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜