Search code examples
ruby-on-railsactiverecordruby-on-rails-5activemodel

How to update Rails Controller to return an error when Model.create errors?


I have the following 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 validates :message, presence: true, length: { in: 1..1000 }

This works great when message is between 1 to 1000 in length. If the controller is submitted more than 1000 characters, the controller is still respond back but without the error.

What is the right way in Rails 5 to have the controller return an error if the create method above fails?


Solution

  • The usual rails way is to test the return value of .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
    

    You can use this doc to find the right statuts code to return https://cloud.google.com/storage/docs/json_api/v1/status-codes