Skip to content

Rails 5.1 saved_changes is broken when updating parent_id on existing model #271

Closed
@schovi

Description

@schovi

Having simple model

class Category < ApplicationModel
  has_closure_tree order: :position
  before_save :show_changes
  after_save :show_saved_changes

  def show_changes
    p "changes #{changes}"
  end

  def show_saved_changes
    p "saved_changes #{saved_changes}"
  end
end

When updating position attribute or other model attributes it behave as expected. But when I change parent_id it will print

changes {"parent_id": [1, 2]}
saved_changes {}

The problem seems to be in closure tree after_save callback in if branch for not a new record.

if public_send(changes_method)[_ct.parent_column_name] && !@was_new_record
  # Resetting the ancestral collections addresses
  # https://github.com/mceachen/closure_tree/issues/68
  ancestor_hierarchies.reload
  self_and_ancestors.reload
end

which will obviously reload and clear model.

Quick solution is to put my callbacks before initializing closure tree in model

class Category < ApplicationModel
  before_save :show_changes
  after_save :show_saved_changes

  has_closure_tree order: :position
end

But it is not that pretty and you can run to other issues.

PS: think if there is more things which can break due to closure tree saving

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions