2017-08-01 10 views
1

Iは、次のコントローラを有する:Model.createエラーが発生したときにエラーを返すようにRails Controllerを更新するには?

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 が検証:メッセージ、プレゼンス:真、長さ:{で:1 1000}

メッセージが間にあるときは、この素晴らしい作品1〜1000の長さ。コントローラーが1000文字を超えて提出された場合、コントローラーは引き続き応答しますが、エラーは発生しません。

上記のcreateメソッドが失敗した場合にコントローラがエラーを返す正しい方法は何ですか?

おかげ

答えて

2

は、通常のレールウェイが.saveの戻り値をテストすることです:

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 

あなたはhttps://cloud.google.com/storage/docs/json_api/v1/status-codes

を返すために、右statutsコードを見つけるために、このドキュメントを使用することができます
関連する問題