使用ruby on rails在json中发送错误消息

时间:2021-09-21 20:25:14

I am validating input fields in ruby on rails. I checking whether user have entered or filled these fields or not. If lets say name field is not filled then send an error message to user with indication that name field is not filled. Same goes with other errors. How can I send this kind of message in json using ruby on rails.

我正在验证ruby on rails上的输入字段。我检查用户是否输入或填写了这些字段。如果让我们说名称字段未填充,则向用户发送错误消息,表明未填写名称字段。其他错误也是如此。如何使用ruby on rails在json中发送此类消息。

Here is what I am doing right now.

这就是我现在正在做的事情。

this model

这个模型

validates :email, :name, :company, :presence => true
validates_format_of :email, :with => /\A[a-z0-9!#\$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#\$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z/

Here is how I am currently sending json data to client

这是我目前如何向客户端发送json数据

@contacts = Contact.new(params[:contact])

if @contacts.save
  render :json => { :error => 0, :success => 1 }
else
  render :json => { :error => 1, :success => 0 }
end

2 个解决方案

#1


15  

The simplest way would be to send down a hash of the errors.

最简单的方法是发送错误的哈希值。

so:

所以:

render :json => { :errors => @contacts.errors.as_json }, :status => 420

note that :status => 420 is required to make things like jquery's $.ajax method call their error callback and you should never return a 200 status (the default) when there is an error.

请注意:status => 420需要使jquery的$ .ajax方法调用其错误回调,并且在出现错误时不应返回200状态(默认值)。

#2


1  

You really should use http status codes to tell the user what is going on, so for invalid record there is

你真的应该使用http状态代码告诉用户发生了什么,所以对于无效记录有

420 Invalid Record  Record could not be saved

And then in your JSON return you could also have an error message that would return your active record / active model error messages in it to give them more information.

然后在您的JSON返回中,您还可能会收到一条错误消息,该消息将返回其中的活动记录/活动模型错误消息,以便为其提供更多信息。

#1


15  

The simplest way would be to send down a hash of the errors.

最简单的方法是发送错误的哈希值。

so:

所以:

render :json => { :errors => @contacts.errors.as_json }, :status => 420

note that :status => 420 is required to make things like jquery's $.ajax method call their error callback and you should never return a 200 status (the default) when there is an error.

请注意:status => 420需要使jquery的$ .ajax方法调用其错误回调,并且在出现错误时不应返回200状态(默认值)。

#2


1  

You really should use http status codes to tell the user what is going on, so for invalid record there is

你真的应该使用http状态代码告诉用户发生了什么,所以对于无效记录有

420 Invalid Record  Record could not be saved

And then in your JSON return you could also have an error message that would return your active record / active model error messages in it to give them more information.

然后在您的JSON返回中,您还可能会收到一条错误消息,该消息将返回其中的活动记录/活动模型错误消息,以便为其提供更多信息。