0

I've generated Devise for User and now I want to add multiple columns after the email column:

class AddColumnsToUser < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :name, :string, after: :email
    add_column :users, :surname, :string, after: :name
    add_column :users, :phone, :integer, after: :surname
    add_column :users, :favourites, :integer, after: :favourites
  end
end

but this code adding these columns at the end of table. I use sqlite3 as database in my app. Is it possible to do it in this configuration (rails 7 + sqlite3)?

Daniel
  • 1
  • Most RDBMS wont actually let you reorder the columns without recreating the entire table. If the column order actually matters you're almost certainly doing something very wrong. I also don't understand where you got `after: :email` when no such option exists. https://api.rubyonrails.org/v7.0.2.3/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column – max Apr 23 '22 at 10:38
  • Email column is generated by Devise in this case. I was based on https://stackoverflow.com/questions/15481733/ruby-on-rails-add-a-column-after-a-specific-column-name It works well with rails 4. – Daniel Apr 23 '22 at 10:51
  • I doubt it worked in Rails 4 either since SQLite doesn't actually let you redefine the column order - altering the table will always add the columns on the end. And doing so would do nother except satisfy your OCD when viewing the table in admin tools. Column order does not matter. – max Apr 23 '22 at 11:16
  • If you really want to do this you would have to rename the table. Create a new table with all the columns in the order you want and then move all the data from the old table to the new table. https://stackoverflow.com/questions/20574113/sqlite3-how-to-reorder-columns-in-a-table – max Apr 23 '22 at 11:21
  • The `after:` option most likely just worked in MySQL. https://stackoverflow.com/questions/2934312/how-to-rearrange-mysql-columns – max Apr 23 '22 at 11:29
  • Thank you for answer. This rails 4 app use MySQL, so it depends on type of database, not rails version. – Daniel Apr 23 '22 at 11:56

0 Answers0