Modify Tables with `change_table` in Rails
Ever since I used ecto in Elixir Phoenix, I've always thought about their alter table
function while working on Rails projects. Turns out, I have been living under a rock and I could have been using change_table
this whole time 🤦🏻♂️
For those new to the change_table
function, it allows you to make bulk alterations to a single table with one block statement. You can adjust columns(and their types), references, indexes, indexes, etc. For a full list of transformations, see the official api documentation.
If you're using Postgres or MySQL, you can also add an optional argument bulk: true
and it will tell the block to generate a bulk SQL alter statement.
class AddUserIdToPosts < ActiveRecord::Migration[7.1]
def change
change_table(:posts, bulk: true) do |t|
t.remove_reference :user_post, :text, null: false
t.references :user, null: false
end
end
end
API Ruby on Rails - change_table
Hooray Rails! 🥳
Tweet