用户在 Rails 中指定的动态模型字段 [英] User specified dynamic model fields in Rails

查看:18
本文介绍了用户在 Rails 中指定的动态模型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道允许用户向模型添加字段的 gem 或好的实现?

Does anyone know of a gem or a good implementation of allowing the user to add fields to a model?

例如

用户希望向联系人模型添加内部注释"字段.在界面中,他们只需选择新字段">类型:文本"

User would like to add a "internal notes" field to the contact model. In the interface they would just select "New field" > "Type: Text"

谢谢

推荐答案

很抱歉,我不知道有任何插件可以做到这一点.但我有一个实施建议.

I'm sorry I don't know of any plugin to do that. But I have an implementation suggestion.

我们的想法是添加一个DynamicField"模型,该模型与 Contact 模型具有 has_many 关系.如果 Contact 模型中缺少某个方法,则检查是否有动态字段可以检索它(如果是这种情况).

The idea is to add a "DynamicField" model which would be a has_many relation to the Contact model. When you have a method missing in the Contact model, you check if there's a dynamic field to retrieve it if that's the case.

class DynamicField < ActiveRecord::Base
    belongs_to :contact
end


class Contact < ActiveRecord::Base
    has_many :dynamic_fields

    def method_missing(sym, *args, &block)
        begin
            super
        rescue
            field = dynamic_fields.find_by_name(sym)
        end
        raise ActiveRecord::NoMethodError if field.nil?
        field.value
    end
end

如果要使用 attribute= 方法添加虚拟属性,则需要添加正则表达式(检测="的存在并进行更新而不是仅获取值).但你已经有了这个想法.

You will need to add a regex if you want to add virtual attributes with the attribute= method (detecting the presence of a "=" and doing an update instead of only getting the value). But you already have here the idea.

当方法不存在时,我们检查动态字段是否有同名的.如果没有 (field.nil?),我们会引发 NoMethodError.否则,我们将其退回.

When the method doesn't exists, we check the dynamic fields if there is one with the same name. If there isn't (field.nil?), we raise a NoMethodError. Otherwise, we return it.

因此,您可以使用以下内容获取所有字段的列表:

So you could get a list of all your fields with the following :

Contact.find(:first).dynamic_fields

并使用以下内容检索特定的:

And retrieve a specific one with the following :

Contact.find(:first).my_dynamic_field

这篇关于用户在 Rails 中指定的动态模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆