Connect a Ruby on Rails application to Neon Postgres
Set up a Neon project in seconds and connect from a Ruby on Rails application
Ruby on Rails, also known simply as Rails, is an open-source web application framework written in Ruby. It uses a model-view-controller architecture, making it a good choice for developing database-backed web applications. This guide shows how to connect to a Ruby on Rails application to a Neon Postgres database.
To connect to Neon from a Ruby on Rails application:
- Create a Neon Project
- Create a Rails Project
- Configure a PostgreSQL Database using Rails
- Create a Rails Controller
- Run the application
This guide was tested using Ruby v3.3.0 and Rails v7.1.2.
Create a Neon Project
If you do not have one already, create a Neon project.
- Navigate to the Projects page in the Neon Console.
- Click New Project.
- Specify your project settings and click Create Project.
Create a Rails Project
Create a Rails project using the Rails CLI, and specify PostgreSQL as the database type:
You now have a Rails project in a folder named neon-with-rails
.
Configure a PostgreSQL Database using Rails
Create a .env
file in the root of your Rails project, and add the connection string for your Neon compute. Do not specify a database name after the forward slash in the connection string. Rails will choose the correct database depending on the environment.
note
You can find the connection string for your database in the Connection Details widget on the Neon Dashboard. For more information, see Connect from any application.
important
The role you specified in the DATABASE_URL
must have CREATEDB privileges. Roles created in the Neon Console, CLI, or API, including the default role created with a Neon project, are granted membership in the neon_superuser role, which has the CREATEDB
privilege. Alternatively, you can create roles with SQL to grant specific privileges. See Manage database access.
Create the development database by issuing the following commands from the root of your project directory:
Create a Rails Controller to Query the Database
Run the following command to create a controller and view. The controller will query the database version and supply it to the view file to render a web page that displays the PostgreSQL version.
Replace the controller contents at app/controllers/home_controller.rb
with:
Replace the contents of the view file at app/views/home/index.html.erb
with:
Replace the contents of config/routes.rb
with the following code to serve your home view as the root page of the application:
Run the application
Start the application using the Rails CLI from the root of the project:
Visit localhost:3000/ in your web browser. Your Neon database's Postgres version will be displayed. For example:
Need help?
Join our Discord Server to ask questions or see what others are doing with Neon. Users on paid plans can open a support ticket from the console. For more detail, see Getting Support.
Last updated on