开发者

User specified dynamic model fields in Rails

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

Ex.

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

Thanks


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

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

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.

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


Here's another way of doing it.

Disclaimer: This method is not advised because of it's potential for abuse. In fact, it should only be accessible for Administrators of your site.

class MyModel < ActiveRecord::Base
  ...
  def self.add_column(name, type, args= {})
    ActiveRecord::Migration.add_column table_name, name, type, args
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜