【问题标题】:Rails migration with a different user than regular connections使用与常规连接不同的用户进行 Rails 迁移
【发布时间】:2020-08-19 21:03:41
【问题描述】:

如何在运行 rails 迁移时使用其他用户连接到数据库?

用例是为迁移创建一个不同于用于运行网络服务器的 Postgres 用户。因此,常规网络服务器数据库用户仅限于 CRUD 获取数据,但没有授予或 DROP 等能力。

为了实现这一点,我需要 Rails 迁移与具有完全创建和删除表访问权限的不同用户一起运行。 (Creds 可以存在于 Rails 加密的凭据文件中,但将它们存储在服务器上的 ENV 中可能没问题)。

所以,要明确一点,设置用户不是问题,我可以做到。我只是想知道是否有最佳实践方法来更改rails db:migrate使用的用户/信用

【问题讨论】:

    标签: ruby-on-rails database migration


    【解决方案1】:

    您可以创建一个新环境,该环境在config/database.yml 中配置了自己的数据库用户。示例:

    default: &default
        adapter: postgresql
        database: dev_db_name
        username: dev_user_name
        password: dev_password
    
    development:
        <<: *default
    
    production:
        <<: *default
        database: production_db_name
        username: production_user_name
        password: production_user_password
    
    migrations:
        <<: *default
        database: production_db_name
        username: migration_user_name
        password: migration_user_password
    

    因此,当您运行迁移时,您必须指定新环境:

    RAILS_ENV=migrations rake db:migrate
    

    重要提示:创建新环境时,请务必完成以下必要步骤:

    1. 创建一个新的config/environments/YOUR_ENVIRONMENT.rb 文件
    2. 如果您的应用程序使用数据库,请在 config/database.yml 中创建一个新的数据库配置条目
    3. config/secrets.yml 中为 Rails 4.1 及更高版本上的应用创建一个新的密钥基础条目

    更多信息click here

    【讨论】:

    • +1 这是一种巧妙的方法。我想你的意思是RAILS_ENV=migrations rake db:migrate,而不是db:migrations,对吧?
    【解决方案2】:

    您可以通过ENV["DATABASE_URL"]设置数据库连接。这优先于config/database.yml 中的任何设置并与它合并:

    DATABASE_URL=postgresql://localhost/some_other_database?username=max&password=p4ssw0rd rails db:migrate
    

    如果你想做一些更高级的事情,比如使用加密凭据来存储密码,我建议你写a custom rake task

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2011-05-21
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多