简体   繁体   中英

Rails: namespaced model is not loaded

I use Rails4, and I created a subfolder in app/models, but I do not why, the rails cannot load the files under the subfolder.

This is my BasicForm in app/models/common/basic_form.rb directory:

class Common::BasicForm < ActiveRecord::Base

    def name=(value)
        super(value.downcase!)
    end

    def phone=(value)
       super(value.blank? ? nil : value.gsub(/[^\w\s]/, '')) 
    end

end

Here the child class of BasicForm:

class Event < Common::BasicForm

    validates   :name,          presence: true
    validates   :description,   presence: true
    validates   :city,          presence: true
    validates   :address,       presence: true
    validates   :event_start,   presence: true
    validates   :event_end,     presence: true
    validates   :phone,         presence: true, length: { maximum: 20, too_long: "%{count} characters are allowed"}     
end

In the config/application.rb I added this config.autoload_paths += [ config.root.join('app') ] line:

module MyApp
  class Application < Rails::Application
    config.autoload_paths += [ config.root.join('app') ]
  end
end

I restarted the server, but I still get this error:

Unable to autoload constant Common::BasicForm, expected /vagrant/MyApp/app/models/common/basic_form.rb to define it

Which is not true, cause the nano in linux can open the basic_form.rb:

vagrant@rails-server-dev:/vagrant/MyApp$ nano /vagrant/MyApp/app/models/common/basic_form.rb

And the nano cans open the basic_form.rb file

I have googled for this problem, or about namespacing models, but I have not found more informations... What do I miss? Which step is missing?

If I move the basic_form.rb to app/models, and remove the 'Common' namespace, the application will be fine.

You have not defined the module namespace Common , so it does not exist yet. Try this:

module Common
  class BasicForm < ActiveRecord::Base
    # class code ...
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM