Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Rails true enum support #163

Merged
merged 1 commit into from
May 29, 2023

Conversation

bgvo
Copy link
Contributor

@bgvo bgvo commented May 18, 2023

I first found this thread and gave Rails enum a shot. It "seemed" to work, but it only did for String mappings. Even if enum was defined, when assigning attributes, jsonb_accessor would update the jsonb with the value from the public getter, which returns the corresponding enum key (whatever that is) and not the actual value that should be stored in the database.

This was first noticed by kg-currenxie.

Example

Given:

jsonb_accessor :data, my_enum_attribute: :integer
enum my_enum_attribute: { "Foo" => 1, "Bar" => 2 }

MyClass.create(my_enum_attribute: "Foo") will store a jsonb with "Foo" as value instead of 1.

With the introduced changes, the actual value stored will be 1.

The use of enums with integers allows a ton of flexibility when it comes to altering existing enum keys. I'm in the middle of a migration and having enums defined with integers instead of strings makes things much easier.

@bgvo
Copy link
Contributor Author

bgvo commented May 18, 2023

I didn't have time to add documentation just yet. Happy to do it if the PR looks good.

@haffla
Copy link
Contributor

haffla commented May 24, 2023

@bgvo thanks. This looks great. Can you fix the lint issues. Then let's see if all tests are green.

@bgvo bgvo force-pushed the mimic_rails_enum_behavior branch from a382bfd to 5d8d5fd Compare May 24, 2023 16:06
@bgvo
Copy link
Contributor Author

bgvo commented May 24, 2023

@haffla Thank you for the excellent work. Lint issue fixed!

@haffla
Copy link
Contributor

haffla commented May 27, 2023

@bgvo can you please remove the change in the schema.rb? It seems to break the test suite and is unrelated to this PR.

@bgvo bgvo force-pushed the mimic_rails_enum_behavior branch from 5d8d5fd to 4b41545 Compare May 29, 2023 09:42
@bgvo
Copy link
Contributor Author

bgvo commented May 29, 2023

@haffla Done. Sorry about that.

@haffla haffla merged commit b050934 into madeintandem:master May 29, 2023
30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants