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

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

问题描述

有谁知道一个宝石还是不错的实现,让用户字段添加到模型的?

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模型,该模型将是一个的has_many相对于联系模式。 当你有一个方法,在接触模型中丢失,你是否有一个充满活力的领域,以获取它,如果是这样的话。

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

您将需要添加一个正则表达式,如果你想与属性=法(检测的=的presence,做只得到了价值的更新代替)添加虚拟属性。 但是,你已经有了这里的想法。

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天全站免登陆