muichkine
muichkine

Reputation: 2940

Access Models in subfolders

I'm having this problem about accessing a Model in a subfolder. I have the following file structure in my project:

app/models
   - accounts
     - type1.rb #Inherits from Account
     - type2.rb #Inherits from Account
     - etc.   
   - account.rb
   - user.rb
   - etc.

Now in user.rb I have a function that tries to create accounts of type1 or type2:

def function
   self.account = ::Type1.new(...)
end

knowing that I added to my application.rb (following http://blog.hasmanythrough.com/2008/5/6/a-simple-alternative-to-namespaced-models) the following line:

config.autoload_paths += Dir["#{config.root}/app/models/**/"]

so that the model subfolders are indeed loaded.

Now, I still get the famous uninitialized constant Type1 error message when I call up the function. What am I missing?

UPDATE:

The Type1 class is empty:

class Type1 < Account
end

and the Account class is straightforward:

class Account < ActiveRecord::Base

#======================RELATIONS======================
  belongs_to :currency
  belongs_to :organization

#======================VALIDATIONS=========================
  validates :name, :presence => true
  validates :country, :presence => true
  validates :currency, :presence => true
  validates :organization, :presence => true
end

Upvotes: 0

Views: 631

Answers (2)

muichkine
muichkine

Reputation: 2940

OK, I finally found the thing. The idea came from this page: Rails 3 library not loading until require

My problem was actually the file name wat not respecting the CamelCase name of the class...

Upvotes: 0

Abhay Kumar
Abhay Kumar

Reputation: 1618

Try this

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

Upvotes: 3

Related Questions