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
Post a Comment