chanzuckerberg / sorbet-rails

A set of tools to make the Sorbet typechecker work with Ruby on Rails seamlessly.
MIT License
638 stars 84 forks source link

Enum override in ActiveRecordOverrides breaks with Rails 7 #479

Closed connorshea closed 2 years ago

connorshea commented 2 years ago

Describe the bug:

Due to changes to the enum method in Rails 7, the code for Enum generation in sorbet-rails appears to be pretty broken. This PR seems to be relevant: https://github.com/rails/rails/pull/41328

I think the code in this file needs to be updated to support Rails 7's enum method: https://github.com/chanzuckerberg/sorbet-rails/blob/8337c1cea41490b0c21fb67153129912eeb3504a/lib/sorbet-rails/rails_mixins/active_record_overrides.rb

Steps to reproduce:

# typed: strict
class Event < ApplicationRecord
  validates :event_category, presence: true

  enum event_category: {
    add_to_library: 0,
    change_completion_status: 1,
    favorite_game: 2,
    new_user: 3,
    following: 4
  }
end
sig { returns(T::Hash[T.any(String, Symbol), T.any()]) }
def self.{:event_category=>{:add_to_library=>0, :change_completion_status=>1, :favorite_game=>2, :new_user=>3, :following=>4}}s; end

Which replaces where self.event_categories used to be defined.

Expected behavior:

Enums work and generate correct methods on Rails 7.

Versions:

connorshea commented 2 years ago

It also breaks the enum method entirely since it monkeypatches code which has changed, which causes errors like this:

[1] pry(main)> Event.create!(
  event_category: :new_user,
  eventable_type: 'User',
  eventable_id: 1,
  user_id: 1
)
  TRANSACTION (0.3ms)  BEGIN
  User Load (2.7ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  TRANSACTION (0.5ms)  ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Event category can't be blank
from /Users/connorshea/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/activerecord-7.0.1/lib/active_record/validations.rb:80:in `raise_validation_error'
ghiculescu commented 2 years ago

@connorshea thanks for reporting. Would you be open to making a PR to fix this? I'm happy to help / review since I helped write https://github.com/chanzuckerberg/sorbet-rails/pull/250 but I won't have capacity to take the lead on it over the next few weeks.

bbugh commented 2 years ago

@ghiculescu this is hurting us too, would you be able to give a brief summary of how this might be fixed? I can PR but I'm not sure where to start.

eabartlett commented 2 years ago

@ghiculescu - currently setting up sorbet in our teams application that just updated to Rails 7, any estimate for when a release version will be made with the merged fix #512?

ghiculescu commented 2 years ago

Just pushed 0.7.34 to rubygems.