应用程序中插件的模型设计
Model design for addons in an app
我有一个 Rails 应用程序,用户可以在其中订阅插件,该列表是动态的,目前包含大约 10 个插件。
列表指定 on/off。
每个插件都有一组相当独特的属性。
我目前的解决方案是该应用程序有 2 个 "parent" 模型和每个插件的一个新模型:
class AddonPrototype
has_many :addons
end
class Addon
belongs_to :addon_prototype
belongs_to :user
end
class AddonAlpha
belongs_to :addon
end
class AddonBeta
belongs_to :addon
end
etc..
模型AddonPrototype
每个插件都有一个实例,默认名称是唯一的属性。
具有属性 enabled
、custom_name
的模型 Addon
。当用户访问带有插件的页面时,会检查用户是否为每个现有 AddonPrototype
拥有一个 Addon
实例,或者即时创建一个。
每个插件都有一个独特的模型(例如 AddonAlpha
、AddonBeta
等),具有适合每个特定插件的一组属性。
这个设计感觉很笨重,有什么可以更精简的设置吗?
我可能遗漏了一些细节,所以请对这个 post 持保留态度。
目前,模型的命名似乎有点误导。 AddonPrototype
是一个实际的插件,而 Addon
模型表示用户安装插件的行为。
这是我想要的结构:
# app/models/user.rb
class User < ActiveRecord::Base
has_many :installations
has_many :addons, through: :installations
end
# app/models/addon.rb
class Addon < ActiveRecord::Base
has_many :installations
has_many :users, through: :installations
end
# app/models/installation.rb
class Installation < ActiveRecord::Base
belongs_to :addon
belongs_to :user
end
AddonPrototype
已重命名为 Addon
,旧的 Addon
模型已重命名为 Installation
(Subscription
或类似名称一个好名字)。
我建议不要在用户访问插件页面时为每个插件创建 Installation
记录。只需在用户实际安装插件时创建这些记录。这使您的代码更简单,数据库更小。
我有一个 Rails 应用程序,用户可以在其中订阅插件,该列表是动态的,目前包含大约 10 个插件。
列表指定 on/off。
每个插件都有一组相当独特的属性。
我目前的解决方案是该应用程序有 2 个 "parent" 模型和每个插件的一个新模型:
class AddonPrototype
has_many :addons
end
class Addon
belongs_to :addon_prototype
belongs_to :user
end
class AddonAlpha
belongs_to :addon
end
class AddonBeta
belongs_to :addon
end
etc..
模型
AddonPrototype
每个插件都有一个实例,默认名称是唯一的属性。具有属性
enabled
、custom_name
的模型Addon
。当用户访问带有插件的页面时,会检查用户是否为每个现有AddonPrototype
拥有一个Addon
实例,或者即时创建一个。每个插件都有一个独特的模型(例如
AddonAlpha
、AddonBeta
等),具有适合每个特定插件的一组属性。
这个设计感觉很笨重,有什么可以更精简的设置吗?
我可能遗漏了一些细节,所以请对这个 post 持保留态度。
目前,模型的命名似乎有点误导。 AddonPrototype
是一个实际的插件,而 Addon
模型表示用户安装插件的行为。
这是我想要的结构:
# app/models/user.rb
class User < ActiveRecord::Base
has_many :installations
has_many :addons, through: :installations
end
# app/models/addon.rb
class Addon < ActiveRecord::Base
has_many :installations
has_many :users, through: :installations
end
# app/models/installation.rb
class Installation < ActiveRecord::Base
belongs_to :addon
belongs_to :user
end
AddonPrototype
已重命名为 Addon
,旧的 Addon
模型已重命名为 Installation
(Subscription
或类似名称一个好名字)。
我建议不要在用户访问插件页面时为每个插件创建 Installation
记录。只需在用户实际安装插件时创建这些记录。这使您的代码更简单,数据库更小。