将自定义字段添加到 ROR 应用程序中的对象

Add custom fields to object in ROR application

我在 CRM 平台上工作。

我希望我的用户在 ClientContactLead 对象中添加、编辑和删除自定义字段。这些字段可能是纯文本字段、列表、复选框、标签等。这些字段可能是必需的,也可能不是。这些字段可能有自定义验证(用户将定义)。

假设一家金融公司想向 Client 对象添加收入,另一家公司想向 Lead 对象添加订单配置。

我的问题有 "enterprise-level" 解决方案(ROR gem)吗?

我当然知道 Custom configuration and config gem,但它看起来不够可扩展。

假设您的数据库是关系型的:

我建议使用 Entity-Attribute-Value 模式: https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model.

这是一个 gem: https://github.com/iostat/eav_hashes

此外,document-oriented 数据库MongoDB 将是一个选项,如果您考虑更改数据库。它是无模式的,因此您可以为不同的实例设置不同的属性。

很难问,但这就是我尝试处理它的方式:我会让所有对象都派生自 CustomField 对象,然后我会在它和对象之间创建一对多关系一个 Field 模型。像这样:

create_table :field_types do |t|
  t.string :name  # This would identify the fields: checkbox, plain text, etc
end

create_table :fields do |t|
  t.belongs_to :custom_field, null: false, index: true
  t.belongs_to :field_type, null: false, index: true
  t.string :name
end

class Field < ApplicationRecord
  belongs_to :custom_field
  belongs_to :field_type
end

class CustomField < ApplicationRecord
  has_many :fields
end

这样您就可以查看数据库中的指定字段并将其装载到视图中。

然后我会为每种类型的字段创建一个 table,用户可以使用它来保存来自 CustomField 对象的数据。例如,我会检查客户端字段说明符,安装一个带有复选框 A 和 B 的视图。然后,我将从复选框中获取数据并将每个数据保存在 table Checkboxes 中并带有标识符,这样我就可以知道它来自客户。

根据您需要执行的操作,我突然想到的另一个想法是将数据作为 JSON 字符串保存到数据库中。这样您就可以拥有具有不同值的不同字段,您需要做的就是序列化和反序列化以分别从数据库中保存和加载它。

抱歉,如果有点混乱。希望对你有帮助。

我不知道有任何开箱即用的选项可用,但无论如何你最好自己动手做这样的事情。它将为您提供更大的灵活性,并且实施起来应该不会太糟糕。在模型方面,我可能会为字段使用 single-table 继承 table,可能使用 jsonb 列作为自定义选项(假设 postgres):

create_table :fields do |t|
  t.string :type, null: false # TextField, ListField, etc.
  t.jsonb :config, default: {}, null: false
  t.belongs_to :contact
end

然后您可以根据需要对不同的 use-cases:

进行子类化
class Field < ApplicationRecord
  belongs_to :contact
end

class TextField < Field
  def required=(required)
    config[:required] = required
  end
end

class CheckboxField < Field
  def default_checked=(default_checked)
    config[:default_checked] = default_checked
  end
end

您可以查看 jsonb_accessor 之类的内容,以创建更清晰的 jsonb 列界面。

同样,single-table 继承看起来对联系人也有意义,不确定基础 table 应该是什么,但可能是这样的:

create_table :contacts do |t|
  t.string :type, null: false # Contact, Lead, Client
end

class Contact < ApplicationRecord
end

class Lead < Contact
end

以下是我发现对自定义字段有帮助的一些示例:

并且: