Rails 6 introduces if_not_exists when creating data tables

Tram Ho

Rails 6 adds an if_not_exists option to create_table option of creating a table if it does not exist.

The default value of if_not_exists is false

Before Rails 6 could we do this? Absolutely, but the way it will be written is longer.

Before rails 6 we used ActiveRecord :: Base.connection.table_exists? to check if a table exists when create_table

1. Rails 5.2

Create a users table in Rails 5.2

Now recreate the users table with the option if_not_exists

We can see that rails 5.2 ignores the if_not_exists option, and tries to recreate the table

Now try ActiveRecord :: Base.connection.table_exists? with rails 5.2

Based on the above results we can see that create_table: :users have not been run because ActiveRecord::Base.connection.table_exists?('users') returns true.

2. Rails 6

Now create users table in rails 6 with if_not_exists = true

Look at the example above. We can see no exceptions are made when we create the second user

Now recreate the users table with the option if_not_exists = false

An exception is fired because the if_not_exists = false option

This is a related pull request

Reference source https://blog.bigbinary.com/2019/05/22/rails-6-adds-if_not_exists-option-to-create_table.html https://api.rubyonrails.org/v5.2/classes/ ActiveRecord / ConnectionAdapters / SchemaStatements.html # method-i-table_exists-3F

Share the news now

Source : Viblo