質問

THE SHORT VERSION: How do I tell Rails to autoload an ActiveRecord class called ClassName that isn't located in the default location (app/models/class_name.rb). E.g. what if it's in app/models/subdirectory/class_name.rb and I don't want to rename the class to Subdirectory::ClassName?

THE LONGER VERSION:

I know that, by default in Rails, my class names have to follow a specific structure for Rails to be able to autoload them.

E.g. If my class is called Person, if I put it in app/models/person.rb, Rails can load it fine, but if I put it in e.g. app/models/person_class.rb, it can't. If I namespace it, e.g. Humanity::Person, I need to put it in the right folder app/model/humanity/person.

(Plus I can put classes in lib but I'll leave aside that detail for now)

So far so good. But what happens when I have a ton of ActiveRecord classes clogging up my app/models folder and I want to logically organise them into directory, but don't want to rename or namespace the actual classes? How can I tell Rails to autoload this classes?

Or is there a good reason why I shouldn't do this?

役に立ちましたか?

解決

Add this line to config/application.rb

config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**/}')]

Then you can use your model with their name as it is without name-spacing.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top