BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

Rails 6 allows spaces in postgres table names

This blog is part of our Rails 6 series.

Rails 6.0 was recently released.

Rails 6 allows spaces in tables names in PostgreSQL. Before Rails 6, if we try to create a table named as user reviews, Rails tries to create a table named as reviews in schema named as user.

Let's checkout how it works.

Rails 5.2

Let's create a table user reviews in Rails 5.2.

1>> class CreateUserReviews < ActiveRecord::Migration[5.2]
2>>   def change
3>>     create_table 'user reviews' do |t|
4>>       t.string :value
5>>
6>>       t.timestamps
7>>     end
8>>   end
9>> end
10
11=> :change
12
13>> CreateUserReviews.new.change
14-- create_table("user reviews")
15CREATE TABLE "user"."reviews" ("id" bigserial primary key, "value" character varying, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
16
17=> Traceback (most recent call last):
18        2: from (irb):10
19        1: from (irb):3:in 'change'
20ActiveRecord::StatementInvalid (PG::InvalidSchemaName: ERROR:  schema "user" does not exist)
21LINE 1: CREATE TABLE "user"."reviews" ("id" bigserial primary key, "...
22                     ^
23: CREATE TABLE "user"."reviews" ("id" bigserial primary key, "value" character varying, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)

We can see that Rails 5.2 raised an exception and tried to create table named as reviews in user schema.

Rails 6.0.0.beta2

Now, let's create a table user reviews in Rails 6.

1>> class CreateUserReviews < ActiveRecord::Migration[6.0]
2>>   def change
3>>     create_table 'user reviews' do |t|
4>>       t.string :value
5>>
6>>       t.timestamps
7>>     end
8>>   end
9>> end
10
11=> :change
12
13>> CreateUserReviews.new.change
14-- create_table("user reviews")
15CREATE TABLE "user reviews" ("id" bigserial primary key, "value" character varying, "created_at" timestamp(6) NOT NULL, "updated_at" timestamp(6) NOT NULL)
16
17=> #<PG::Result:0x00007f9d633c5458 status=PGRES_COMMAND_OK ntuples=0 nfields=0 cmd_tuples=0>

Now, we can see that the SQL generated is correct and Rails successfully created a table named as user reviews.

Here is the relevant pull request.

Amit Choudhary in Rails 6
June 5, 2019
Share

Subscribe to our newsletter