diff --git a/lib/jsonb_accessor/macro.rb b/lib/jsonb_accessor/macro.rb index 03e25e7..63c309f 100644 --- a/lib/jsonb_accessor/macro.rb +++ b/lib/jsonb_accessor/macro.rb @@ -91,9 +91,8 @@ def jsonb_accessor(jsonb_attribute, field_types) empty_named_attributes = names_to_store_keys.transform_values { nil } empty_named_attributes.merge(value_with_named_keys).each do |name, attribute_value| - # Undefined keys: There might be things in the JSON that haven't been defined using jsonb_accessor - # It should still be possible to save arbitrary data in the JSON - next unless has_attribute? name + # Only proceed if this attribute has been defined using `jsonb_accessor`. + next unless names_to_store_keys.key?(name) write_attribute(name, attribute_value) end diff --git a/spec/jsonb_accessor_spec.rb b/spec/jsonb_accessor_spec.rb index 975c5f1..7d05346 100644 --- a/spec/jsonb_accessor_spec.rb +++ b/spec/jsonb_accessor_spec.rb @@ -8,6 +8,8 @@ def build_class(jsonb_accessor_config, &block) self.table_name = "products" jsonb_accessor :options, jsonb_accessor_config instance_eval(&block) if block + + attribute :bang, :string end end @@ -274,6 +276,12 @@ def build_class(jsonb_accessor_config, &block) expect(subklass_instance.sub).to be_nil end end + + it "does not write a normal Ruby attribute" do + expect(instance.bang).to be_nil + instance.options = { bang: "bang" } + expect(instance.bang).to be_nil + end end context "dirty tracking for already persisted models" do