如何在 Model.create 错误时将 Rails 控制器更新为 return 错误?
How to update Rails Controller to return an error when Model.create errors?
我有以下控制器:
class Api::V1::FeedbacksController < ApplicationController
before_action :authenticate_user!
def create
@feedback = current_user.feedbacks.create(
feedback_type: params[:selectedType],
message: params[:message]
)
json_response(@feedback)
end
private
def json_response(object, status = :ok)
render json: object, status: status
end
end
Feedback.rb
验证 :message, presence: true, length: { in: 1..1000 }
当消息的长度在 1 到 1000 之间时,这很有效。如果控制器提交超过 1000 个字符,控制器仍然响应但没有错误。
如果上面的创建方法失败,Rails 5 中让控制器 return 出错的正确方法是什么?
通常的rails方法是测试.save
的return值:
def create
@feedback = current_user.feedbacks.new(
feedback_type: params[:selectedType],
message: params[:message]
)
if @feedback.save
json_response(@feedback)
else
json_response(@feedback.errors, :some_other_status)
# you could also send @feedback directly and then in your JSON response handler
# to test if the json contains values in the object.errors array
end
end
private
def json_response(object, status = :ok)
render json: object, status: status
end
您可以使用此文档找到 return https://cloud.google.com/storage/docs/json_api/v1/status-codes
的正确状态代码
我有以下控制器:
class Api::V1::FeedbacksController < ApplicationController
before_action :authenticate_user!
def create
@feedback = current_user.feedbacks.create(
feedback_type: params[:selectedType],
message: params[:message]
)
json_response(@feedback)
end
private
def json_response(object, status = :ok)
render json: object, status: status
end
end
Feedback.rb 验证 :message, presence: true, length: { in: 1..1000 }
当消息的长度在 1 到 1000 之间时,这很有效。如果控制器提交超过 1000 个字符,控制器仍然响应但没有错误。
如果上面的创建方法失败,Rails 5 中让控制器 return 出错的正确方法是什么?
通常的rails方法是测试.save
的return值:
def create
@feedback = current_user.feedbacks.new(
feedback_type: params[:selectedType],
message: params[:message]
)
if @feedback.save
json_response(@feedback)
else
json_response(@feedback.errors, :some_other_status)
# you could also send @feedback directly and then in your JSON response handler
# to test if the json contains values in the object.errors array
end
end
private
def json_response(object, status = :ok)
render json: object, status: status
end
您可以使用此文档找到 return https://cloud.google.com/storage/docs/json_api/v1/status-codes
的正确状态代码