How to show all the errors that merged to a single model serializer?
khrisnagunanasurya-iav opened this issue · 0 comments
khrisnagunanasurya-iav commented
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
- Create 2 models,
FirstModel
andSecondModel
- On
FirstModel
there are 3 attributes,attr_a, attr_b, and attr_c
- On
SecondModel
there are 2 attributes,attr_x and attr_z
FirstModel
HAS MANYSecondModel
SecondModel
BELONGS TOFirstModel
- On create / save on
SecondModel
, it will validate the data onFirstModel
based on if condition that checking the current date, and let's assume it will check ifattr_a
is a valid date, if it's not valid, then it will add errors toFirstModel
- On
Secondmodel
custom validate, it will get the errors from the associated model, and merge the errors toSecondModel
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