DmitryTsepelev / store_model

Work with JSON-backed attributes as ActiveRecord-ish models
MIT License
1.04k stars 85 forks source link

ActiveRecord validation contexts don't propagate #141

Closed penguoir closed 1 year ago

penguoir commented 1 year ago

Hi! I came across some surprising behaviour. Happy to submit a pull request if this is a bug:

class User
  attribute :configuration, Configuration.to_type
  validates :configuration, store_model: { merge_errors: true }
end

class Configuration
  attribute :favourite_number, type: :integer
  validates_presence_of :favourite_number, on: :custom_validation_context
end

user = User.new
user.configuration = {favourite_number: nil}

# Validate with no set context
user.valid? #=> true (expected)

# Validate with custom_validation_context
user.valid?(:custom_validation_context) #=> true (not expected)

When we a model validate with a specific context, I expect its stores to be validated under the same context. So when I validate user.valid?(:context), we should validate the configuration under the same context: user.configuration.valid?(:context).

Instead, the context is discarded and configuration is validated with no specific context.

I think this is the line that causes this behaviour: https://github.com/DmitryTsepelev/store_model/blob/62514a65c810922a78632885c79ba4355305b074/lib/active_model/validations/store_model_validator.rb#L34

DmitryTsepelev commented 1 year ago

Hey @penguoir! Agreed, sounds like a bug, can't wait to review and merge the PR ☺️