forest-rails
forest-rails copied to clipboard
fix: don't eager load the models if pending DB migrations
Context:
Rails 7 app with an existing User model.
Issue:
We update our AR model User by adding an enum named access_level
(the name is not important).
So we generate a migration, define the new column (access_level
) and add the enum
statement in the User model.
When running the rails db:migrate
command, it fails withe following message:
/Users/johndoe/.rbenv/versions/3.3.5/lib/ruby/gems/3.3.0/gems/activerecord-7.1.3.4/lib/active_record/enum.rb:250:in `block in _enum': Undeclared attribute type for enum 'access_level'. Enums must be backed by a database column or declared with an explicit type via `attribute`. (RuntimeError)
The problem is that the ForestAdmin engine eager loads all the AR models and executes the enum
class method within the models. Rails expects the column to exist in DB but since we're running the migration, well the famous egg -> chicken issue.
Solutions:
Solution 1: don't require ForestAdmin in the Gemfile and require in the application.rb
file only if we're not running rails db:migrate
. This involves a lot of if defined?(ForestLiana)
in the code. 🙅🏻
Solution 2: don't eager load the models in the ForestAdmin engine IF there are pending migrations. 👌
Definition of Done
General
- [x] Write an explicit title for the Pull Request, following Conventional Commits specification
- [ ] Test manually the implemented changes
- [x] Validate the code quality (indentation, syntax, style, simplicity, readability)
Security
- [ ] Consider the security impact of the changes made