store_attribute
store_attribute copied to clipboard
`store_attribute_register_attributes = true` causes validation failures and incorrect attribute values
When using store_attribute_register_attributes = true, there seems to be some funky interplay with Rails' attribute system. Some examples are validators checking the wrong values (e.g. #52 ), the attributes hash showing incorrect data, and other attribute-related methods returning unexpected results.
Example:
class User < ApplicationRecord
self.store_attribute_register_attributes = true
store_attribute :settings, :age, :integer, default: 18
validates :age, numericality: { greater_than_or_equal_to: 0 }
end
What happens:
user = User.new
user.age = -5
# Validation incorrectly passes
user.valid? # => true (Expected false)
user.errors[:age] # => [] (Expected "must be greater than or equal to 0")
# Attribute methods show inconsistent values
user.age # => -5 (correct)
user.attributes["age"] # => 18 (Expected -5, is showing default instead of actual value)
user.settings["age"] # => -5 (correct)
# After saving and reloading
user.save!(validate: false)
reloaded = User.find(user.id)
reloaded.age # => -5 (correct)
reloaded.attributes["age"] # => 18 (Expected -5, is showing default instead of actual value)
reloaded.valid? # => true (Expected false)
This issue affects multiple Rails features beyond validation:
- Dirty tracking: age_before_type_cast returns the default instead of the actual value
- Mass assignment: Setting values through attributes= doesn't always sync with the store
- Serialization: as_json may include default values instead of actual values
- Callbacks: Attribute values in callbacks may be inconsistent
I suspect that we may need to add a synchronization layer that keeps store attribute changes synced with Rails' Attributes.