命名空间模型导致UndefinedTable错误

Kre*_*eki 4 activerecord ruby-on-rails

我有以下命名空间模型:

# 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
Run Code Online (Sandbox Code Playgroud)

和数据库架构如下:

# 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
Run Code Online (Sandbox Code Playgroud)

该应用程序运行正常但在启动时(服务器,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
Run Code Online (Sandbox Code Playgroud)

它只发生在生产中(不在开发环境中),看起来它在运行时没有效果(应用程序继续运行良好 - 生成的查询使用正确的表名).

请注意,FaceData应用程序中还有其他命名空间模块和类.table_name_prefix显式设置为空字符串不会使错误消失.

我的猜测是它与加载文件的顺序或has_many :through关联有关.有小费吗?

r3b*_*o0t 11

为了避免所有这些问题,你可以做一件事.app/models/face_data.rb用这些内容创建一个

    module FaceData
      def self.table_name_prefix
        'face_data_'
      end
    end
Run Code Online (Sandbox Code Playgroud)

有了这个,您就不再需要为self.table_name在同一范围内定义的每个类编写代码.如果您有任何疑问,请告诉我.