Rails - helps to use models in subfolders

I am using Rails 4 and ActiveAdmin with SQLite.

1. I created these models and moved the files to folders:

app
  models
    system
       - admin_user.rb
       - customer.rb
    resources
       - document.rb

2. Added to config / application.rb:

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

3. In the model files, I simply added a prefix to the model name:

class System::AdminUser < ActiveRecord::Base
    # Include default devise modules. Others available are:
    # :confirmable, :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable,
           :recoverable, :rememberable, :trackable, :validatable
    # Include default devise modules. Others available are:
    # :confirmable, :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable,
           :recoverable, :rememberable, :trackable, :validatable
end

-

So, when I try to run rake db:migrate, I get this error:

LoadError: Unable to autoload constant AdminUser, expected /Users/john/testing/app/models/System/admin_user.rb to define it

Am I doing something wrong?

+4
source share
1 answer

Rails automatically manages to find correctly-namespaced classes in subfolders of applications / models without having to do something special. Since you added the application / model subfolders to the startup path, Rails now expects to find classes that do not contain names in these places.

, :

# app/models/system/admin_user.rb
module System
  class AdminUser
    # your code here
    # ...
  end
end

.

+4

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


All Articles