views:

127

answers:

1

I have to create a database schema with Rails migrations.

I have lots of columns which contain quantities (kg) and prices (currency).

Currently I use this:

  t.column :quantity, :decimal, :precision => 6, :scale => 3
  t.column :value, :decimal, :precision => 6, :scale => 2

At the generator call I use quantity:decimal to identify my columns. Then I manually change the generated t.decimal lines to the above.

I don't like this, because after every generated migration I manually have to edit the migration script and I worry about DRY. (What if the price has to contain four instead of two decimal places?)

Is it possible to create a custom column type which I can use in migrations and perhaps even generators, like this:

  t.quantity :quantity
  t.price :value

PS: I'm a Rails noob, I'm sorry if this is a stupid question.

+1  A: 

I'm sure you can do what you are asking-- dig into the column method within the migrations code-- but I don't think it's supported naturally. I think the idea with the migrations are they are pretty close to the databases language (and further from you domain model), so the support is pretty database centric.

Look at using with_options (railscasts.com/episodes/42-with-options). This will allow you to DRY out a single migration without patching rails.

You can also make helper methods within the migration that DRYs it out. I do this all the time... the migration is just a Ruby class, so you could create:

def currency(column) add_column :my_table, column, :deci... etc.

ndp