[英]Association Problems when Inheriting from a Rails Engine Model
I have a shared engine that I keep shared AR models and bunch of other stuff. 我有一个共享引擎,可以保持共享的AR模型和许多其他东西。 Below is my User AR model 下面是我的用户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
And I have a child User in the main rails app ( Analytics
) as follows: 我在主Rails应用程序( Analytics
)中有一个子用户,如下所示:
class User < Shared::User
self.table_name = 'users'
end
When I mount this engine to a rails app, I dynamically find the "correct" ( Analytics::User
) using below method: 当我将此引擎安装到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
With above, I can insert, find records in the database, but problems start when I use associations and AR validators (above validates_uniqueness_of
calls for instance) 通过上面的内容,我可以在数据库中插入,查找记录,但是当我使用关联和AR验证程序时(例如在validates_uniqueness_of
调用之上),问题就开始了
user = model_const('User').create ... # works, returns a Analytics::User instance
user.apps # fails with below error
(Same error if I un-comment validators in the Shared::User model and try to create a new record) (如果我取消对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
):
Also, please note that I'm creating and trying to access apps
in the shared engine code, not sure if that matters. 另外,请注意,我正在创建并尝试访问共享引擎代码中的apps
,不确定是否很重要。
Thanks in advance! 提前致谢!
After spending a good couple of hours, here is the solution that I came up with. 花了几个小时之后,这是我想到的解决方案。 (This is actually what I should have done in the first place, so blame me
) (实际上这是我首先应该做的,所以请blame me
)
Nest outer User class inside Analytics module: 将外部User类嵌套在Analytics模块中:
module Analytics class User.... end end
add this to the lib/shared.rb file
: 将其添加到lib/shared.rb file
:
def self.table_name_prefix end
Hope this could be helpful to someone else.. 希望这对其他人有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.