Rails: organizing models in subfolders having warning: toplevel constant A referenced by B::A

前端 未结 2 396
半阙折子戏
半阙折子戏 2021-01-17 11:08

Today I decided to reorganize big amount of user related models and I\'m having a problem with it.

Before I had such structure:

app/models/user.rb
ap         


        
相关标签:
2条回答
  • 2021-01-17 11:09

    Update: This years Christmas present was the release of Ruby 2.5.0 with which this error won't happen anymore. With Ruby 2.5+ you will either get the constant you asked for or an error. For older Ruby versions read on:

    Your User::File class is not loaded. You have to require it (e.g. in user.rb).

    The following happens when ruby/rails sees User::Info and evaluates it (simplified; only User is defined yet).

    • check if User::Info is defined - it is not (yet)
    • check if Info is defined - it is not (yet)
    • uninitialized constant -> do rails magic to find the user/info.rb file and require it
    • return User::Info

    Now lets do it again for User::File

    • check if User::File is defined - it is not (yet)
    • check if File is defined - it is (because ruby has a built in File class)!
    • produce a warning, because we've been asked for User::File but got ::File
    • return ::File

    We observe that the rails magic, that automatically requires files for (yet) unknown constants, does not work for User::File because File is not unknown.

    0 讨论(0)
  • 2021-01-17 11:28

    Try referring to the class as User::File to distinguish it from regular ruby Files. You can use ::File to refer to those when it is ambiguous

    0 讨论(0)
提交回复
热议问题