How to specify order of field to add using migration in Rails 3?

笑着哭i 提交于 2019-12-12 02:12:50

问题


How can I specify after which field I want to add a new column? (I don't want the field added in at the bottom after the timestamps)

add_column :users, :is_active, :boolean


回答1:


Here is how:

add_column :users, :is_active, :boolean, :after => :some_column

where :some_column is the name of the column you want to add :is_active after.




回答2:


In general, you can't and you shouldn't care. Tables in relational databases don't really have any particular order; that's why you should always specify the columns when you INSERT and never say things like select * ... (yes, ActiveRecord does that but that but that doesn't mean that it is a good idea, just because AR jumps off a cliff doesn't mean you should, etc.).

If you insist on trying to do the database's job for it then the portable way is:

  1. Copy or rename the table to another table.
  2. Drop the original (unless you renamed in (1)).
  3. Create the new table with the columns in the order you want.
  4. Hope the database pays attention to your order in (3).
  5. Copy the data to from the table in (1) to the "new" table from (3).
  6. ...
  7. Profit.

If you're using the MySQL or MySQL2 database adapters, you can use the :after => :some_column option to add_column. If you're using SQLite or PostgreSQL, then see the portable way above. If you're using anything else then you'll have to read the adapater's documentation or source code to see what is supported.

But you should ask yourself why you think you want to do this before proceeding.



来源:https://stackoverflow.com/questions/8335716/how-to-specify-order-of-field-to-add-using-migration-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!