ruby-on-railsrubyexceptionservice-object

Rails API How to add errors in exception and continue


In my Rails project I created service object which get params and save Model. I want to handle exception there when e.g. one of the params is not valid. My service object looks like that:

class ModelSaver
  include ActiveModel::Validations

  attr_reader :model

  def initialize(params)
    @params = params
  end

  def errors
    @model.errors
  end

  def save_model
    @model ||= Model.new(params)

    @model.name = nil
    @model.save!

  rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid => error
    @model.errors.add(:base, error.to_s)
    false
  end

  private

  attr_reader :params
end

In Model name can't be nil, so when in example I try to @model.name = nil then service object go to rescure and exit from save_model. Can I somehow continue and add next errors from @model.save! (if there any) after exception from @model.name = nil?


Solution

  • Unsure what are you trying to achieve but I assume you've just removed all the business logic from the model and left only the bare minimum in that code sample.

    I'd suggest instead of calling save! just call save and check if the object is valid. If it's not continue to do what you want to do or add additional errors, if it's valid then do something else.

    Example of how that might look like:

      def save_model
        @model ||= Model.new(params)
    
        @model.name = nil
        @model.save
    
        return true if @model.valid?
        
        @model.add(:name, :invalid, message: "can't be nil")
        ... some code
      end
    

    But instead of that, I'd suggest adding a custom validator instead of trying to reinvent the wheel here you have a guide on how to use it: https://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations