2017-08-01 68 views
1

我有以下的控制器:如何更新Rails Controller以在Model.create錯誤時返回錯誤?

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方法失敗,Rails 5中控制器返回錯誤的正確方法是什麼?

感謝

回答

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 

您可以使用該文檔來找到合適的statuts代碼返回https://cloud.google.com/storage/docs/json_api/v1/status-codes