Rails - Adding Custom Fields at runtime in ActiveRecord

后端 未结 3 1859
深忆病人
深忆病人 2021-02-03 12:55

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:

3条回答
  •  不知归路
    2021-02-03 12:58

    Something like...?

    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
    

提交回复
热议问题