activerecord - How to validate parent-child relationships in Rails? -


i have category model can have multiple parent , child categories. have modelled using hierarchy model contains parent_category , child_category attributes.

i can validate rows unique using

validates_uniqueness_of :parent_category_id, scope: :child_category_id

this (and corresponding unique index in database) takes care there not multiple rows representing same parent-child relationship.

but, want prevent assigning parent of child it's child. ex. if category parent of category b, assigning category child of category b should result in validation error.

the approach can think of querying database in validate method.

def child_parent_messup   unless hierarchy.where(child_category_id: parent_category_id, parent_category_id: child_category_id).blank?       errors[:base] << "this child parent of same class."    end end 

how can improved?

what referring 'cyclic' relationship - and, imho, there no default validator built rails this.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -