我有一个共享引擎,我保持共享AR模型和其他一些东西。 以下是我的用户AR模型
module Shared
class User < ApplicationRecord
validates_presence_of :password, on: :create
# validates_uniqueness_of :email
# validates_uniqueness_of :phone_number
has_many :apps
end
end
我在主轨道应用程序(Analytics
)中有一个子用户,如下所示:
class User < Shared::User
self.table_name = 'users'
end
当我将此引擎安装到rails应用程序时,我使用以下方法动态查找“正确”(Analytics::User
):
def model_const(const)
# shell_app is set to 'Analytics' somewhere else
shell_app.constantize.const_get const
rescue
Shared.const_get const
end
上面,我可以插入,在数据库中查找记录,但是当我使用关联和AR验证器时会出现问题(例如,validates_uniqueness_of
以上的调用)
user = model_const('User').create ... # works, returns a Analytics::User instance
user.apps # fails with below error
(如果我在Shared :: User模型中取消注释验证器并尝试创建新记录,则会出现相同的错误)
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: relation "shared_apps" does not exist
LINE 8: WHERE a.attrelid = '"shared_apps"'::regclas...
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
(SELECT c.collname FROM pg_collation c, pg_type t
WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation),
col_description(a.attrelid, a.attnum) AS comment
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"shared_apps"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
):
此外,请注意我正在创建并尝试访问共享引擎代码中的apps
,不确定这是否重要。
提前致谢!
答案 0 :(得分:0)
花了好几个小时后,这就是我提出的解决方案。 (这实际上是我本来应该做的,所以blame me
)
在Analytics模块中嵌套外部用户类:
module Analytics
class User.... end
end
将此添加到lib/shared.rb file
:
def self.table_name_prefix
end
希望这对其他人有帮助..