Structure of the dynamic attributes table

ramontayag edited this page May 8, 2011 · 2 revisions

Although you probably shouldn’t work with it directly, the dynamic_attributes table looks like this:

ActiveRecord::Base.connection.create_table(:dynamic_attributes) do |t|
  t.string :name, :null => false
  t.string :attr_key, :null => false
  t.string :object_type, :null => false
  t.string :attributable_type, :null => false
  t.integer :attributable_id, :null => false
  %w(integer string boolean text float).each do |type|
    t.send(type, "#{type}_value".to_sym)
  end
end

This means that depending on the type of dynamic attribute you’re creating, things will get saved in the respective column in the dynamic_attributes table.

@user.add_dynamic_attribute(:gunslinger, "boolean")

adds this to the dynamic_attributes table:

{ 
  :attr_key => "gunslinger", 
  :attributable_id => [the user's id],
  :attributable_type => "User",
  :object_type => "boolean",
  :boolean_value => true
}

Why have different value columns? Because I couldn’t find any other way to perform SQL operations/calculations on a generic “value” column. Besides, what kind of column would that be? A text blob?

Dynamic attribute “type”

Here are the different types of dynamic attributes you can save:

  • string
  • text
  • integer
  • float
  • boolean

If you assign a value to a dynamic attribute that isn’t the original type, it is ignored.

@user.write_dynamic_attribute :gunslinger, true
@user.save
@user.read_dynamic_attribute(:gunslinger) # true
@user.write_dynamic_attribute :gunslinger, "hey there"
@user.save
@user.read_dynamic_attribute(:gunslinger) # true