diff --git a/CHANGELOG.md b/CHANGELOG.md index 7961e0c..548e8e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ ## master +- [PR #205](https://github.com/DmitryTsepelev/store_model/pull/205) Fix value handling for enums ([@DmitryTsepelev]) + ## 4.2.1 (2025-02-01) - [PR #200](https://github.com/DmitryTsepelev/store_model/pull/200) Don't use #to_h on store model instances in OnePolymorphic types ([@23tux]) diff --git a/lib/store_model/types/enum_type.rb b/lib/store_model/types/enum_type.rb index 75fc0b4..55a96a9 100644 --- a/lib/store_model/types/enum_type.rb +++ b/lib/store_model/types/enum_type.rb @@ -45,7 +45,10 @@ def cast_value(value) private def cast_symbol_value(value) - raise_invalid_value!(value) if @raise_on_invalid_values && !@mapping.key?(value.to_sym) + raise_invalid_value!(value) if @raise_on_invalid_values && + !@mapping.key?(value.to_sym) && + !@mapping.values.include?(value) + @mapping[value.to_sym] || value end diff --git a/spec/store_model/enum_spec.rb b/spec/store_model/enum_spec.rb index 64bf3bd..cf51765 100644 --- a/spec/store_model/enum_spec.rb +++ b/spec/store_model/enum_spec.rb @@ -249,4 +249,36 @@ def self.model_name end end end + + describe "persistance" do + class ProductConfiguration + include StoreModel::Model + + enum :color, in: { red: "ee0000", green: "00ee00", blue: "0000ee" } + end + + class Product < ActiveRecord::Base + attribute :product_configuration, ProductConfiguration.to_type, default: ProductConfiguration.new + end + + before do + Product.create!(product_configuration: { color: color }) + end + + context "when key is used" do + let(:color) { :green } + + specify do + expect(Product.last.product_configuration).to be_green + end + end + + context "when value is used" do + let(:color) { "00ee00" } + + specify do + expect(Product.last.product_configuration).to be_green + end + end + end end