导轨 - 添加自定义字段在运行时的ActiveRecord [英] Rails - Adding Custom Fields at runtime in ActiveRecord
本文介绍了导轨 - 添加自定义字段在运行时的ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您知道一些bug跟踪系统(以及其他软件)如何让你添加自定义字段?
You know how some bug trackers (and other software) allow you to add custom fields?
通常这是一个数据结构,看起来像这样完成的:
Typically this is done with a data structure that looks something like this:
Items
----------
ID | NAME | ITEM_TYPE_ID
FieldDefinitions
---------------------------------------
ID | ITEM_TYPE_ID | FIELD_NAME | FIELD_TYPE
FieldValues
---------------------------------------
ID | FIELD_ID | ITEM_ID | VALUE
我试图找出处理这个设计的Rails的最佳途径。将有很多车型,我想允许扩展简单的属性。
I'm trying to figure out the best way to approach this design in Rails. There will be many models which I want to allow extending simple properties.
当我retreive一个项目
我想它包括已被定义为模型添加字段值的哈希值。
When I retreive an Item
I'd like it to include a hash of the addition field values that have been defined for that model.
推荐答案
喜欢的东西...?
class Item < ActiveRecord::Base
has_many :field_values
has_many :field_definitions, :through => :field_values
def custom_fields_hash
cfh = {}
self.field_values.each |fv|
cfh[fv.field_definition] = fv
end
cfh
end
end
class FieldValue < ActiveRecord::Base
belongs_to :item
belongs_to :field_definition
end
class FieldDefinition < ActiveRecord::Base
has_many :field_values
has_many :items, :through => field_values
end
或者,你可以改变
Or, you could change
cfh[fv.field_definition] = fv
...到...
...to...
cfh[fv.field_definition.field_name] = fv.value
这篇关于导轨 - 添加自定义字段在运行时的ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文