-
Notifications
You must be signed in to change notification settings - Fork 104
Open
Labels
help wantedExtra attention is neededExtra attention is needed
Description
Hi,
It appears that enum when using custom values are completly broken. It always raises something like ArgumentError: invalid value 'fr-CA' is assigned
I tried debugging and it seems internally StoreModel::Types::EnumType#cast_integer_value(value) is called properly with 'fr' but then is called a second time with the already converted value (fr-ca)
Note: This happens on the record loading, record update, record assignation, etc.
Setting raise_on_invalid_values: false will get rid of the error but will persist the enum key in database instead of the value.
Here is a reproduction test
# frozen_string_literal: true
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
gem 'rails'
gem 'minitest-rails'
gem 'pg'
gem 'store_model'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
ActiveRecord::Base.establish_connection(adapter: 'postgresql', database: 'test', host: 'localhost', port: 5437, username: 'dev', password: 'dev', query_cache: false)
ActiveRecord::Base.logger = Logger.new(nil)
ActiveRecord::Schema.define do
create_table 'users', force: :cascade do |t|
t.string :name
t.jsonb :organization
end
end
class Organization
include StoreModel::Model
attribute :id, :integer
# attribute :locale, :string
enum :locale, in: { en: "en-CA", fr: "fr-CA" }
end
class User < ActiveRecord::Base
include StoreModel::NestedAttributes
attribute :organization, Organization.to_type
accepts_nested_attributes_for :organization, reject_if: :all_blank, update_only: true
end
describe "StoreModel Bug" do
def test_organization_with_valid_locale_should_be_loadable
ActiveRecord::Base.connection.execute(<<-SQL)
INSERT INTO users (id, name, organization)
VALUES (1, 'John Doe', '{ "id": 1, "locale": "fr-CA" }');
SQL
db_locale = ActiveRecord::Base.connection.execute(<<-SQL)
SELECT organization->>'locale' FROM users WHERE id = 1;
SQL
assert_equal "fr-CA", db_locale.first.values.first
user = User.find(1)
assert_equal "fr", user.organization.locale
end
def test_it_updates_locale
user = User.create!(name: "John Doe", organization: { id: 1, locale: :fr })
assert_equal "fr", user.organization.locale
user.organization.locale = :en
user.save!
db_locale = ActiveRecord::Base.connection.execute(<<-SQL)
SELECT organization->>'locale' FROM users WHERE id = 1;
SQL
assert_equal "en", user.organization.locale
assert_equal "en-CA", db_locale.first.values.first
end
endMetadata
Metadata
Assignees
Labels
help wantedExtra attention is neededExtra attention is needed