Cached attribute definition (attr_cached)

This commit is contained in:
cryptogopher 2025-04-19 20:29:29 +02:00
parent 1cddc794d2
commit fe66522c21
2 changed files with 15 additions and 4 deletions

View File

@ -1,3 +1,17 @@
class ApplicationRecord < ActiveRecord::Base class ApplicationRecord < ActiveRecord::Base
class << self
# Cached attribute has non-user assignable value calculated from other
# attributes' values on create/update. This simplifies and speeds up
# actions, especially for recursively calculated values. Because value can
# be changed on update, it is not same as #attr_readonly.
def attr_cached(*names)
names.each { |name| alias_method :"#{name}=", :assign_cached_attribute }
end
end
def assign_cached_attribute(value)
raise ActiveRecord::ReadonlyAttributeError
end
primary_abstract_class primary_abstract_class
end end

View File

@ -1,5 +1,6 @@
class Quantity < ApplicationRecord class Quantity < ApplicationRecord
ATTRIBUTES = [:name, :description, :parent_id] ATTRIBUTES = [:name, :description, :parent_id]
attr_cached :depth, :pathname
belongs_to :user, optional: true belongs_to :user, optional: true
belongs_to :parent, optional: true, class_name: "Quantity" belongs_to :parent, optional: true, class_name: "Quantity"
@ -70,10 +71,6 @@ class Quantity < ApplicationRecord
self[:depth] = parent&.depth&.succ || 0 self[:depth] = parent&.depth&.succ || 0
end end
def depth=(value)
raise ActiveRecord::ReadonlyAttributeError
end
scope :defaults, ->{ where(user: nil) } scope :defaults, ->{ where(user: nil) }
# Return: ordered [sub]hierarchy # Return: ordered [sub]hierarchy