Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 model. In the interface they would just select "New field" > "Type: Text"

Thanks

like image 212
Recode Avatar asked Oct 17 '09 17:10

Recode


1 Answers

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
like image 177
Damien MATHIEU Avatar answered Nov 03 '22 22:11

Damien MATHIEU