在Rails Admin中使用具有多态关联的名称空间模型



在RailsAdmin中,我试图用两个类来管理我的多态Region,一个有名称空间,另一个没有名称空间。

class Region < ApplicationRecord
belongs_to :contentable, polymorphic: true
end
class Event::Exhibition < ApplicationRecord
has_many :regions, as: :contentable
end
class Post < ApplicationRecord
has_many :regions, as: :contentable
end

除了名称空间模型实例的ajax获取之外,一切都正常。

例如,当我尝试选择Event::Exhibition时,我会在浏览器的控制台中看到它。

Error: Syntax error, unrecognized expression: #event::exhibition-js-options rails_admin.js:1502:8
error http://localhost:3000/assets/rails_admin/rails_admin.js:1502

当我选择Post时,我的所有帖子都会按预期返回。

这是一个错误吗?还是我应该用不同的设置来解决这个问题?对此,我唯一的配置是告诉Rails管理员使用该字段。

edit do
field :contentable
end

深入研究HTML和JavaScript(感谢@Guillermo(,我注意到生成的下拉列表如下所示。

<option value=""></option>
<option value="Event::ArtFair">Art fair</option>
<option value="Event::Exhibition">Exhibition</option>
<option selected="selected" value="Post">News article</option>

当选择了值为Event::的任一选项时,Sizzle会抱怨,并引发语法错误。

在我的代码检查器中,如果我转义冒号,使值Event::ArtFairEvent::Exhibition按预期工作。

我明白了,这些都不是有效的js标识符。我认为,如果您通过添加_enum实例方法来定义select的内容,则可以对值进行scape处理。

首先,您需要获得模型的可能内容列表。

我是从臀部开枪,但应该是这样的:

def self.contentable_models
ActiveRecord::Base.descendants.select do |model|
model.reflect_on_all_associations(:has_many).any? do |has_many_association|
has_many_association.options[:as] == :contentable
end
end
end
def contentable_enum
self.class.contentable_models.map |model|
[
model.name.humanize,
model.class.name.gsub(':',':')
]
end
end

我不确定contentable_models的性能——如果你有很多模型,它会对所有模型进行迭代,以找到你可能想要记忆该值的内容。

您可能需要将contentable字段定义为enum,甚至contentable_type字段。不确定

最新更新