Given:
def Node belongs_to :parent, class_name: :Node has_many :children, class_name: :Node, foreign_key: :parent_id end
I am trying to create a check to make sure that Node cannot be its own parent or parent, etc.
I got it:
And it works completely! This is actually a problem. It works. When Rails calls the assign_attributes method, I get 422, but it doesn't have my check! Instead, I get an ugly HTML validation error like this:
ActiveRecord::RecordNotSaved (Failed to replace children because one or more of the new records could not be saved.)
So, if Rails cannot save related records, Rails returns its own error (the one that is in the code block above), but if my record is self-related, I get a big problem. Even if I stopped Node from checking related child / parent objects, I still get an error message.
While the record I'm trying to save TSELF has an error, then Rails replaces my 422 with the error above. And this is just bad. I want a JSON response error so that my client knows what exactly went wrong.
It’s hard for me to believe that no one else has encountered this problem, have I missed something?
source share