18

I'm trying to add a new column, 'latitude', to an existing Postgres table, after the 'location' column.

Using this syntax puts the column in the correct place:

add_column :table, :column, :decimal, :after => :existing_column

And using this syntax ensures that the field is the correct data type

add_column :table, :column, :decimal, {:precision => 10, :scale => 6}

But when I try and combine the two:

add_column :table, :column, :decimal, {:precision => 10, :scale => 6}, :after => :existing_column

I get "ArgumentError: wrong number of arguments (5 for 3..4)"

"Not to worry", I thought, "I'll just combine the arguements!":

add_column :table, :column, :decimal, {:precision => 10, :scale => 6, :after => :existing_column}

But then the columns appear at the end of the table. What am I doing wrong?

Thanks :)

Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
Joe Czucha
  • 4,123
  • 2
  • 20
  • 28
  • 1
    [The order of the columns is totally irrelevant in relational databases](http://stackoverflow.com/questions/1243547/how-to-add-a-new-column-in-a-table-after-the-2nd-or-3rd-column-in-the-table-usin) – dax Nov 30 '14 at 14:27
  • 4
    Yep I'm aware of that, but I kind of like keeping related things together just from a sanity point of view... – Joe Czucha Nov 30 '14 at 14:59
  • in `add_column` method no such option `:after => :existing_column`. allowed options you can find in [documentation for this method](http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_column#637-Options) – Roman Kiselenko Nov 30 '14 at 15:04
  • @Зелёный there is such option. I used it in my Rails 3.1 project with MySQL and it worked perfectly. – Rustam Gasanov Nov 30 '14 at 15:12
  • @RustamA.Gasanov show me documentation please for this option. – Roman Kiselenko Nov 30 '14 at 15:12
  • @Зелёный I can't see available options in documentation(you reference is not on documentation either), but I can say it for sure because I used it. [Check the relevant SO answer](http://stackoverflow.com/a/15481778/644810) and [one more](http://stackoverflow.com/a/8336005/644810) – Rustam Gasanov Nov 30 '14 at 15:20
  • @RustamA.Gasanov ok, my bad, i use only `pg` and never `mysql`. +1 for hidden feature. – Roman Kiselenko Nov 30 '14 at 15:24

1 Answers1

27

Your last definition is correct. But the problem here isn't with Rails, but with PostgreSQL, which doesn't allow to add a column at specific position. Read more: How can I specify the position for a new column in PostgreSQL?

Community
  • 1
  • 1
Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
  • 2
    Ah, silly me, I'd not tested the :after option since moving from MYSQL to Postgres. Good catch, thanks :) – Joe Czucha Nov 30 '14 at 15:25