Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 291
AnApprentice Avatar asked Apr 10 '26 22:04

AnApprentice


1 Answers

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

like image 66
MrYoshiji Avatar answered Apr 13 '26 15:04

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!