ruby on rails - Model callbacks not working with self referential association -


i having model evaluation has many sub evaluations (self refential)

class evaluation < applicationrecord    has_many :sub_evaluations, class_name: "evaluation", foreign_key: "parent_id", dependent: :destroy    before_save :calculate_score    def calculate_score     #   end  end 

i creating , updating evaluation sub evaluations nested attributes.

calculate_score method triggered on sub evaluation creation not while updating. have tried before_update , after_validation. nothing seems working.

evaluation form

= form_for @evaluation |f|   ...   = f.fields_for :sub_evaluations |sub_evaluation|    ... 

what seems issue?

this article helped me fix issue.

child callback isn't triggered because parent isn't "dirty".

the solution in article "force" dirty calling attr_name_will_change! on parent attribute that, in fact, not change.

here updated model code:

class evaluation < applicationrecord    has_many :sub_evaluations, class_name: "evaluation", foreign_key: "parent_id", dependent: :destroy    before_save :calculate_score    def calculate_score     #   end    def exam_id= val     exam_id_will_change!     @exam_id = val   end  end 

see active model dirty in rails api


Comments

Popular posts from this blog

Combining PHP Registration and Login into one class with multiple functions in one PHP file -

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -