stas/jsonapi.rb

How to show all the errors that merged to a single model serializer?

khrisnagunanasurya-iav opened this issue · 0 comments

Expected Behavior

Show merged errors from another model. because there will be a lot of validations, so I want to merge the errors.

Actual Behavior

undefined method 'error_attribute_from_another_model_that_merged'

Steps to Reproduce the Problem

  1. Create 2 models, FirstModel and SecondModel
  2. On FirstModel there are 3 attributes, attr_a, attr_b, and attr_c
  3. On SecondModel there are 2 attributes, attr_x and attr_z
  4. FirstModel HAS MANY SecondModel
  5. SecondModel BELONGS TO FirstModel
  6. On create / save on SecondModel, it will validate the data on FirstModel based on if condition that checking the current date, and let's assume it will check if attr_a is a valid date, if it's not valid, then it will add errors to FirstModel
  7. On Secondmodel custom validate, it will get the errors from the associated model, and merge the errors to SecondModel object

Code that merge the errors

class Bookings
 ...
  private 

  def check_user
    return if user.able_to_book?

    errors.merge!(user.errors)
  end

  def check_lesson
    return if lesson.bookable_by_user?(user)
    
    errors.merge!(lesson.errors)
  end

Booking Serializer

class BookingSerializer
  include JSONAPI::Serializer
  
  attributes :waiting_list, :canceled_at

  belongs_to :user
  belongs_to :lesson
  belongs_to :lesson_schedule
end

User model

  def able_to_book?
    if active_languages.none?
      errors.add :base, :no_active_lang

      return false
    end

    errors.add :free_trial_chances, :used_up if is_trial? && !free_trial_chances?
    errors.add :base, :suspended if suspended?

    errors.none?
  end

Specifications

  • Version: 1.7
  • Ruby version: 3.0.0