Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rails find models and controllers? How can I get it to load more models?

I'm trying to create a non-ActiveRecord model in app/models/gamestate.rb. Then inside my controller (PlayController) I should be able to do GameState.new, right? No go:

NameError (uninitialized constant PlayController::GameState):
  app/controllers/play_controller.rb:23:in `play'

(at least in the development environment)

But! If I do have a model called app/models/play.rb, then it's automatically loaded and I can do Play.new.

So my question is: how does Rails know which classes to load? What sort of name mangling does it do to get from play#action to PlayController to app/controllers/play_controller.rb to app/models/play.rb?

It seems awfully fragile, but maybe a better understanding of how this works would help.

And finally, how can I get it to load app/models/gamestate.rb?

like image 319
PBJ Avatar asked Nov 28 '22 18:11

PBJ


1 Answers

Heikki is right, but doesn't explain why it's this way. Rails adds every folder inside app to the autoload_path config setting. When an unknown constant is asked for, Rails will look up in this path to find the constant and if it can't find a filename -- such as the case of gamestate.rb vs. the proper game_state.rb -- then it won't be able to load the constant defined in this file.

like image 192
Ryan Bigg Avatar answered Dec 21 '22 23:12

Ryan Bigg