0

What I need to do is I want to be able to create a table with dynamic columns, retrieving column name and its data type out of a hash.

Please take the code snippet below for example:

COLUMNS =  { :column1 => 'integer',
                :column2 => 'string',
                :column3 => 'string',
                :column4 => 'date'
                }

In the static way, I could do like this:

create_table :details do |t|
  t.integer column1
  t.string column2
  t.string column3
  t.date column4
  t.timestamps
end

But, you know, that looks a bit hard-coded, and I'm not happy with that.

My idea is to make it more like:

create_table :details do |t|

  COLUMNS.each_pair do |key,value|
    #to define each column and its data type
    t[value] key
  end

  t.timestamps  
end

Unfortunately, it doesn't seem to work for me the way I want.

1 Answer 1

1

t.integer is calling a method on t, not doing an array index, so have you tried instead calling t.__send__(value, key) ?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.