SegFaultDev
SegFaultDev

Reputation: 583

Using Postgres Schema with Ruby on Rails

I have a separate server that contains a Ruby on Rails API ( DB is postgres) that will used by multiple, different, applications. I was thinking of using schemas to sort the tables that each application will require and have a "common" schema that contains the tables that the applications will share ( Users, Employees, etc). Each application schema would have roughly 10 tables and the common schema would contain about 15. The current plan is to have about 3-5 apps using this API all using the same common tables.

My question is, is it worth implementing Postgres schemas with Ruby on Rails? I've been looking for some resources on the topic, but there doesn't seem to be much information on it. There are a couple articles written in 2011/2012 but nothing closer to 2018. One of the main things I've been looking for is how to create rails migrations with postgres schemas properly.

I also read a comment from a user stating that they have used postgres and rails separately, but would never use them in conjunction.

It feels like a good idea to use schemas to organize the DB but don't want to go down that road if it will require a lot of manual DB work/maintenance.

Thanks,

Upvotes: 4

Views: 2055

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

This can be easily implemented with Rails, you will have to override the default table name expected by Rails to point to a specific Schema though:

class YourSchemaRecord < ApplicationRecord
  self.table_name_prefix = 'name_of_your_schema.'
end

class SomeRecord < ApplicationRecord
end

class YourCommonSchemaRecord < ApplicationRecord
  self.table_name_prefix = 'public.'
end

class SomeCommonRecord < YourCommonSchemaRecord
end

About Rails migrations, you can either use plain SQL (my favorite option) or use Rails' built-in method but give the "full path" of the table you want to update the structure:

add_column 'name_of_your_schema.some_records', :some_column, :string

Upvotes: 7

Related Questions