You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails开发疑问:是否必须执行迁移,仅创建ORM类并定义关联可行吗?

Can I Skip Rails Migrations and Use a Manually Created PostgreSQL Database with Active Record?

Absolutely! You totally can bypass Rails migrations entirely, set up your database schema directly in PostgreSQL, then map it to Active Record models with all the associations you need. This is actually a great fit for folks like you who have a database background and prefer handling schema design directly with SQL—no need to force your database work into Rails' migration syntax if you don't want to.

Here's a step-by-step breakdown of how to make this work:

1. Create Your Database and Tables in PostgreSQL

Fire up psql (or use a GUI like pgAdmin) and build your schema just like you normally would. For example, a simple blog structure:

-- Create the database first
CREATE DATABASE my_blog_db;

-- Connect to the database
\c my_blog_db;

-- Create users table
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  email VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255),
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Create posts table with a foreign key to users
CREATE TABLE posts (
  id SERIAL PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  content TEXT,
  user_id INTEGER REFERENCES users(id),
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Note: Including created_at and updated_at is a good idea if you want Active Record to automatically manage those timestamps when you save records.

2. Generate (or Write) Your Active Record Models

You can either generate models without migrations, or create the model files manually:

  • To generate a model without a migration:
    rails generate model User --no-migration
    rails generate model Post --no-migration
    
  • Or create files in app/models/ yourself. For example, app/models/user.rb:
    class User < ApplicationRecord
      has_many :posts
    end
    
    And app/models/post.rb:
    class Post < ApplicationRecord
      belongs_to :user
    end
    

Handling Non-Standard Names

If your table names or columns don't follow Rails' conventions (e.g., a table named people instead of users), just specify the table name in the model:

class Person < ApplicationRecord
  self.table_name = 'people'
  has_many :posts, foreign_key: 'person_id' # If the foreign key isn't `user_id`
end

3. Configure Your Database Connection

Make sure your config/database.yml points to your manually created PostgreSQL database. A typical development setup might look like this (adjust username/password as needed):

development:
  adapter: postgresql
  database: my_blog_db
  username: your_postgres_username
  password: your_postgres_password
  host: localhost
  port: 5432

4. Key Things to Keep in Mind

  • Primary Keys: Active Record expects a primary key named id by default. If your table uses a different name (e.g., user_id), add self.primary_key = 'user_id' to your model.
  • Foreign Keys: For associations, Active Record looks for foreign keys like user_id for a belongs_to :user association. If your foreign key has a different name, specify it with the foreign_key option (like in the non-standard names example above).
  • Schema Documentation: Even without migrations, you can run rails db:schema:dump to generate a schema.rb file that reflects your current database structure. This helps share your schema with teammates or keep a record of changes.
  • Future Schema Changes: If you need to modify your schema later, you can either run SQL directly in PostgreSQL, or write a Rails migration (just make sure it doesn't try to recreate tables you already have).

Since you have a database background, this approach lets you leverage your SQL skills while still getting all the benefits of Active Record's querying and association features. It's totally valid and widely used in projects where the database schema is designed first, or when working with existing databases.

内容的提问来源于stack exchange,提问作者Wayne E. Pfeffer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:13:18