📜  postgresql rails (1)

📅  最后修改于: 2023-12-03 15:33:44.680000             🧑  作者: Mango

PostgreSQL and Rails

Introduction

PostgreSQL is a popular open-source database management system, while Rails is a web application framework written in Ruby. PostgreSQL and Rails work together gracefully, providing a powerful and flexible solution for scalable web applications. In this guide, we will explore the basics of using PostgreSQL with Rails.

Installation

You will need to install PostgreSQL and Rails separately. To install PostgreSQL, you can follow the instructions on the PostgreSQL website. To install Rails, you can use the gem installer:

gem install rails
Configuration

Once you have installed both PostgreSQL and Rails, you will need to configure your Rails app to use PostgreSQL. First, add the PostgreSQL gem to your Gemfile:

gem 'pg'

Then, run bundle install to install the gem. Next, configure your database settings by modifying config/database.yml:

default: &default
  adapter: postgresql
  host: localhost
  port: 5432
  username: <%= ENV['POSTGRES_USER'] %>
  password: <%= ENV['POSTGRES_PASSWORD'] %>
  database: myapp_development

development:
  <<: *default

test:
  <<: *default
  database: myapp_test

production:
  <<: *default
  database: myapp_production

Replace myapp with the name of your app. You will also need to set the POSTGRES_USER and POSTGRES_PASSWORD environment variables.

Creating a Database

To create a database, run:

rails db:create

This will create a development and test database, as specified in config/database.yml. You can also create a production database by running:

rails db:create RAILS_ENV=production
Migrations

Rails migrations allow you to make changes to your database schema. To create a migration, run:

rails generate migration AddNameToUsers name:string

This will create a migration in the db/migrate directory. You can then run the migration by running:

rails db:migrate

This will add a name column to your users table.

Models

Rails models represent a table in your database. To create a model, run:

rails generate model User name:string email:string

This will create a user model with name and email attributes. You can then run the migration to create the users table:

rails db:migrate
Conclusion

PostgreSQL and Rails are a powerful combination for building scalable web applications. With the ability to handle large amounts of data and the flexibility of the Rails framework, you can build robust web applications that can handle even the most demanding workloads.