加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 导致UndefinedTable错误的命名空间模型

发布时间:2020-12-17 04:01:39 所属栏目:百科 来源:网络整理
导读:我有以下命名空间模型: # app/models/face_data/pool_membership.rbclass FaceData::PoolMembership ActiveRecord::Base self.table_name = 'face_data_pool_memberships' belongs_to :pool,class_name: 'FaceData::Pool' belongs_to :photoend# app/models
我有以下命名空间模型:

# 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.如果您有任何疑问,请告诉我.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读