Last Updated: February 25, 2016
·
3.82K
· we4tech

Simple trick to work with ActiveRecord dynamic column and encapsulated accessor

Just writing this so i can remind if i need it again I’m in the middle of creating a generic flexible domain modeling module (i call it flexi-model).

In brief flexi-model is schema less flexible modeling tool. It can store your data of any kinda it does trick just providing generic value method and pick up the right column type from preset column definition from model class.

Just to make it easier to grasp here is a sample code -

class Product
  include FlexiModel

  flexi_field :name, :string
  flexi_field :price, :decimal

  set_flexi_partition_id USER.store.id
end

I’ve the following structure in -

[Collection - for dynamic schema] -< [Record] -< [Value]

On the form I’m using f.datetime_select :value where (f denotes fields_for of Value instance) after submission rails was trying to figure out what is :value column in table definition. since it’s not an existing column so rails was throwing up MultiparameterAssignmentErrors error.

Just after digging bit deep it looks like readvaluefrom_parameters is responsible for loading real column definition. So to mock it i’ve added the following code and it works –

# Put it on your model instance
def column_for_attribute(name)
  # Put your accessor name, in my case :value
  if :value == name.to_sym
    self.class.columns_hash[self.field.value_column.to_s]
  else
    self.class.columns_hash[name.to_s]
  end
end

thats all :)

Copied from my blog post - http://we4tech.wordpress.com/2012/06/20/simple-trick-to-work-with-activerecord-dynamic-column-and-encapsulated-accessor/