Search code examples
ruby-on-railsrubytypecheckingsorbet

Sorbet-rails not generating RBI's for rails has_many, belongs_to, etc


Maybe there's something in the initialization process that I missed, but sorbet-rails seems to having trouble generating methods for some of the default rails methods (e.g. has_many, belongs_to, validates, etc.). I can see that the corresponding generated association is generated, but I get type complaints that the main methods do not exist.

e.g. a class like this:

class Role < ApplicationRecord
  has_and_belongs_to_many :users, :join_table => :users_roles

I can see the auto generated sigil in role.rbi

  sig { returns(::User::ActiveRecord_Associations_CollectionProxy) }
  def users; end

However this is the error I get when checking types:

Method has_and_belongs_to_many does not exist on T.class_of(Role) https://srb.help/7003
     3 |  has_and_belongs_to_many :users, :join_table => :users_roles
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Solution

  • This error is an error with sorbet not knowing that has_and_belongs_to_many method exists. Usually this is provided by sorbet itself. I can see the signature of this method is defined in sorbet-typed's activerecord.rbi. In your repo it should be under this path:

    sorbet/rbi/sorbet-typed/lib/activerecord/all/activerecord.rbi
    

    Can you check if the file exists in your repo? if not, you could try running srb rbi sorbet-typed (following the rbi files doc)

    Method has_and_belongs_to_many does not exist on T.class_of(Role) https://srb.help/7003
         3 |  has_and_belongs_to_many :users, :join_table => :users_roles
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^