Ruby on rails 数据模型的动态自定义字段
我正在创建一个动态数据库,用户可以在其中创建资源类型,并在其中添加自定义字段(多个文本、字符串和文件) 每种资源类型都能够显示、导入、导出其数据 我一直在考虑这个问题,下面是我的方法。我很想听听你们的想法 想法:Ruby on rails 数据模型的动态自定义字段,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在创建一个动态数据库,用户可以在其中创建资源类型,并在其中添加自定义字段(多个文本、字符串和文件) 每种资源类型都能够显示、导入、导出其数据 我一直在考虑这个问题,下面是我的方法。我很想听听你们的想法 想法: 只需将所有自定义数据散列在一个数据字段中(赞成:写起来更容易,反对:读出来可能更难) 子字段(模型将有多个字符串字段、文本字段和文件路径字段) 同一表中固定数量的自定义字段,其中键映射数据散列存储在同一行中 非SQL方法,但问题是动态生成/更改模型以使用不同的自定义字段 首先,您可以创
首先,您可以创建几个模型:
-StringData
-布尔数据
-文本数据
-文件数据
etc(您需要的所有数据和字段格式) 每个模型将引用到某个项目,其中将包含有关字段的信息 即: 它没有经过测试和优化,但它只是展示了实现它的方法
更新:我已经更新了代码,但这是唯一的模型,您必须稍微考虑一下:)您可以尝试找到另一个实现为什么不为DynamicField创建一个模型呢 栏目:
t.integer :dynamic_field_owner_id
t.string :dynamic_field_owner_type
t.string :name, :null => false
t.string :value
t.string :value_type_conversion, :default => 'to_s'
# any additional fields from paperclip, has_attachment, etc.
t.timestamps
模型类:
class DynamicField > ActiveRecord::Base
belongs_to :dynamic_field_owner, :polymorphic => true
validates_presence_of :name
validates_inclusion_of :value_type_conversion, :in => %w(to_s to_i to_f)
validates :value_or_attachment
def value
read_attribute(:value).send(value_type_conversion)
end
private
def value_or_attachment
unless value? || file?
errors.add_to_base('Must have either value or file')
end
end
end
当我们需要传递某些条件时,如何查询这些自定义字段?我已经更新了答案。但写一条评论是一个相当大的问题。因此,请尝试在本代码上实现您的实现。感谢所有的灵感。我在MongoDB方法上做了一些测试,我想我会继续使用您的类似实现。我仍然有点不确定查询的速度会有多慢。
t.integer :dynamic_field_owner_id
t.string :dynamic_field_owner_type
t.string :name, :null => false
t.string :value
t.string :value_type_conversion, :default => 'to_s'
# any additional fields from paperclip, has_attachment, etc.
t.timestamps
class DynamicField > ActiveRecord::Base
belongs_to :dynamic_field_owner, :polymorphic => true
validates_presence_of :name
validates_inclusion_of :value_type_conversion, :in => %w(to_s to_i to_f)
validates :value_or_attachment
def value
read_attribute(:value).send(value_type_conversion)
end
private
def value_or_attachment
unless value? || file?
errors.add_to_base('Must have either value or file')
end
end
end