rails has_many relation of parent not updated after save

Viewed 267

Simplified code for Rails 5.2.

A very simple Base class that adds up some value of its Items.

class Base < ApplicationRecord
  has_many :items

  def values
    children.map(&:value).sum
  end
end

The Item class which modifies itself:

class Item < ApplicationRecord
  belongs_to: :base

  def increment
    puts parent.values # == 0
    self.value = 10
    save!
    puts parent.values # == 0 #???
  end
end

when calling some_item.increment I'd expect the second parent.values to return 10, but it doesn'T. On the next call it does return 10, somehow this is cached for the first call.

Is there some hidden caching mechanism, or is save! delaying the change?

1 Answers

You must reload the parent object using reload!

class Item < ApplicationRecord
  belongs_to: :base

  def increment
    puts parent.values # == 0
    self.value = 10
    save!
    parent.reload!
    puts parent.values
  end
end
Related