Rails models in subfolders and links

I organized some of my rail models in folders that I upload using

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

I can use all models directly (e.g. Image.first.file_name ), but when I try to access them through relationships, for example. @housing.images.each do... with has_many: images I get the following error

 Unable to autoload constant Housing::HousingImage, expected /path/app/models/housing/image.rb to define it 

How do I get rails for using my models for relationship methods?

I run ruby ​​2.2 and rails 4.2

+5
source share
1 answer

Rails automatically loads models from subfolders, but expects them to have a namespace.

 /app/models/user.rb class User end /app/models/something/user.rb class Something::User end 

If you incorrectly place your models in subfolders, this will ruin the Rails autoloader and cause the errors you see.

Remove this

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

And add the correct namespaces to your models and everything will work fine.

You can easily use models with names in your relationships, for example:

 class User has_many :photos, class_name: 'Something::Photo' end user.photos (will be instances of Something::Photo) 

If you do not want to use the namespace, but share your models for another reason, you can do this at the top level and use other folders next to the models. By default, rails load all folders in applications, so you can simply create the β€œmodels2” folder or whatever you want to name next to β€œmodels”. This will not affect the loading functionality of the rail class.

Based on your example, you can:

 /app /controllers /models for all your normal models /housing for your "housing" models 

Similarly, you can directly access them in the top-level namespace, with no class name parameters or anything else.

+6
source

Source: https://habr.com/ru/post/1213731/


All Articles