我在尝试在我的应用程序上查看页面时不断遇到'非初始化的常数'错误,这就是这样发生的,因为将我的模型捆绑到一个宝石中并在两个应用程序之间共享我的数据库。型号没有加载?
所以我的应用程序路由'页#索引,这是控制器
class PagesController < ApplicationController
def index
@portfolios = Portfolio.all
end
end
很好,简单。所以我收到的错误消息是
uninitialized constant PagesController::Portfolio
im我的数据库.yml文件,我将应用程序指向第二个应用程序开发数据库
database: myblog_development
我像这样的宝石中加载了我的模型,#blogmodels.rb文件
require "blogModels/version"
module BlogModels
Gem.find_files("models/*.rb").each do |f|
filename = File.basename(f, '.*')
class_name_symbol = filename.classify.to_sym
autoload class_name_symbol, "models/#{filename}"
end
end
我的宝石结构
-blogModels
-lib
-blogModels
-version.rb
-models
-portfolio.rb
-sector.rb
-blogModels.rb
和我的投资组合模型在我的宝石
中是这样设置的class Portfolio < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
has_many :portfolio_sectors
has_many :sectors, through: :portfolio_sectors
has_many :images, as: :imageable, :dependent => :destroy
accepts_nested_attributes_for :images
attr_accessible :overview, :title, :url, :sector_ids, :image_id, :images_attributes
#Validations
validates :title, :presence => {:message => 'Add your Title'}
validates :url, :presence => {:message => 'Add a URL'}
validates :overview, :presence => {:message => 'Add an Overview'}
validates :sector_ids, :presence => {:message => 'Choose At Least 1 Sector'}
def previous_post
self.class.first(:conditions => ["title < ?", title], :order => "title desc")
end
def next_post
self.class.first(:conditions => ["title > ?", title], :order => "title asc")
end
end
我不确定该如何调试,因此,如果有人有任何指针,请建议。我对为什么这不起作用感到困惑。
- 确保您的宝石在Gemfile中,并且已重新启动服务器
- 您需要需要包含模型的文件
- 如果您仍面临问题,请检查
::Portfolio
是否适合您 - 作为经验法则,当您将模型(或一般类)移动到宝石中时,将它们放在名称空间模块中,并通过
MyGemName::Portfolio
参考您的类
编辑:
由于您在不同的项目之间共享模型,因此将模型分组为模块
是有意义的module MyAwesomeModels
class Portfolio < ActiveRecord::Base
# self.table_name = 'portfolios' # if you face issues accessing the tables, this might help
end
end