我有以下命名空间模型:
# app/models/face_data/pool_membership.rb class FaceData::PoolMembership < ActiveRecord::Base self.table_name = 'face_data_pool_memberships' belongs_to :pool,class_name: 'FaceData::Pool' belongs_to :photo end # app/models/face_data/pool.rb class FaceData::Pool < ActiveRecord::Base self.table_name = 'face_data_pools' end # app/models/photo.rb class Photo < ActiveRecord::Base has_many :pool_memberships,class_name: 'FaceData::PoolMembership' has_many :pools,through: :pool_memberships,class_name: 'FaceData::Pool' end
和数据库架构如下:
# db/schema.rb create_table "face_data_pool_memberships",force: true do |t| # omitted end create_table "face_data_pools",force: true do |t| # omitted end
该应用程序运行正常但在启动时(服务器,rake任务等)我收到以下错误:
PG::UndefinedTable: ERROR: relation "pool_memberships" does not exist LINE 5: WHERE a.attrelid = '"pool_memberships"'::regc... ^ : SELECT a.attname,format_type(a.atttypid,a.atttypmod),pg_get_expr(d.adbin,d.adrelid),a.attnotnull,a.atttypid,a.atttypmod FROM pg_attribute a LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum WHERE a.attrelid = '"pool_memberships"'::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum
它只发生在生产中(不在开发环境中),看起来它在运行时没有效果(应用程序继续运行良好 – 生成的查询使用正确的表名).
请注意,应用程序中还有其他FaceData命名空间模块和类.将table_name_prefix显式设置为空字符串不会使错误消失.
我的猜测是它与加载文件的顺序或has_many:通过关联有关.有小费吗?
解决方法
为了避免所有这些问题,你可以做一件事.使用这些内容创建app / models / face_data.rb
module FaceData def self.table_name_prefix 'face_data_' end end
这样,您就不再需要为在同一范围内定义的每个类编写self.table_name.如果您有任何疑问,请告诉我.