1

What are the best practices in case you want to build a Rails project that uses an existing Database?

in my case the postgres database living on a remote machine that runs a docker instance with postgres has a database with a table stake_address.

Now I have created a model in Rail:

class StakeAddress < ApplicationRecord
end

in rails console:

2.6.1 :001 > StakeAddress.all
Traceback (most recent call last):
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  relation "stake_addresses" does not exist)
LINE 1: SELECT "stake_addresses".* FROM "stake_addresses" LIMIT $1
                                        ^

is there a way to avoid Rails to look for a pluralised table? I suppose there are going to be many other problems like this, so I was wondering if this is common practice, or if is something out of the world that is highly recommended to avoid?

Also I guess I don't need migrations, because the database is already created. Is that going to cause problems down the line?

My idea is that I will be able to connect to two databases, one read-only already existing and the other one where I can put my own models as Users. But will they be able to create association cross databases?

Perhaps Rails isn't the best framework for this type of work? Is what I am learning during a bootcamp, but perhaps I should switch to more flexible environments?

2
  • 1
    As a solution to your first problem just add self.table_name = 'stake_address' to your model file. And no you don't need migrations. Commented Dec 31, 2020 at 18:21
  • I would use postgres_fdw and link your existing database into the rails specific database. Then your queries can be run against both databases as if they are one. I don't think your can add foreign keys but most things should just work. Commented Dec 31, 2020 at 18:43

1 Answer 1

2

If there are not too many tables, I would also recommend what @eyeslandic suggests and manually override the table names in the models that need it.

self.table_name = 'stake_address'

If there are many tables, you’d be better off in the long run if you renamed them. You can do this safely in production with something like LHM.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.