0

I got the data by 'MODEL.all' command in rails console

I want to put the column 'cgi_name' in the 3rd position when I run MODEL.all in the rails console

I use the postgres for my DB

How to get it ?

enter image description here

newBike
  • 14,385
  • 29
  • 109
  • 192

2 Answers2

3

To answer your question directly, you'll have to move the columns at DB level

Currently, I only know MYSQL to support this functionality:

ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;

Postgres, to my knowledge, does not support this functionality:

Many people new to postgresql often ask if it has support for altering column positions within a table. Currently it does not; if you want to change column positions, you must either recreate the table, or add new columns and move data

In the view, you'll have to either manually display the columns, or create a helper method to cycle through them in an order of your choosing

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • 1
    -1 for suggesting to move the columns at the DB level. That simply is a non-issue, which is why PG does not support it. Use properly crafted SELECT statements or a view instead. – Patrick May 02 '14 at 13:10
  • 2
    Thanks for the downvote. I really appreciate your OPINION that it doesn't matter. I browse at db level and appreciate correctly ordered columns, and if the guy is asking the question; he obviously cares too – Richard Peck May 02 '14 at 14:22
  • Changing column order within the DB is virtually never a solution to a problem. The answer is thus not relevant. It is also not my opinion, it is standard knowledge that an operator should not assume a certain table layout nor care about it. The OP should have been informed that this is not a solution and an alternative should have been presented, as many other posters have done. You may want to check out the current discussion on meta about the quality of questions and answers (and this is not meant to deride the question of the OP). – Patrick May 03 '14 at 08:53
  • It's interesting that they were considering adding ordering back in 2006. Hopefully they'll implement it someday! – Brian Burns Dec 09 '19 at 11:37
2

Simple answer is YOU CANNOT

There is no way to re-order the column names to be displayed when you select using Model.all.

Otherwise, you can re-order this by selecting each column in the order you want.

Model.select("column1, column2, cgi_name, column4 etc..")

Hope it helps :)

Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85