在 Rails 模型中使用多个 PostgreSQL 模式 [英] Using multiple PostgreSQL schemas with Rails models

查看:14
本文介绍了在 Rails 模型中使用多个 PostgreSQL 模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Rails 应用程序有一个 PostgreSQL 数据库.在名为public"的模式中,存储了主要的 Rails 模型表等.我创建了一个discogs"模式,其中的表的名称有时与public"模式中的名称相同 - 这是原因之一我正在使用模式来组织它.

I have a PostgreSQL database for my Rails application. In the schema named 'public' the main Rails models tables are stored etc. I have created a 'discogs' schema which will have tables with names that are sometimes the same as in the 'public' schema - which is one of the reasons that I'm using schemas to organize this.

我将如何从我的应用程序中的discogs"模式设置模型?我也将使用 Sunspot 让 Solr 索引这些模型.我不确定你会怎么做.

How would I setup models from the 'discogs' schema in my app? I will be using Sunspot to let Solr index these models as well. I'm unsure of how you would do this.

推荐答案

database.yml 中的 PostgreSQL 适配器 schema_search_path 是否解决了你的问题?

PostgreSQL adapter schema_search_path in database.yml does solve your problem?

development:
  adapter: postgresql
  encoding: utf-8
  database: solidus
  host: 127.0.0.1
  port: 5432
  username: postgres
  password: postgres
  schema_search_path: "discogs,public"

或者,您可以为每个架构指定不同的连接:

Or, you can to specify different connections for each schema:

public_schema:
  adapter: postgresql
  encoding: utf-8
  database: solidus
  host: 127.0.0.1
  port: 5432
  username: postgres
  password: postgres
  schema_search_path: "public"

discogs_schema:
  adapter: postgresql
  encoding: utf-8
  database: solidus
  host: 127.0.0.1
  port: 5432
  username: postgres
  password: postgres
  schema_search_path: "discogs"

定义每个连接后,创建两个模型:

After each connection defined, create two models:

class PublicSchema < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :public_schema
end

class DiscoGsSchema < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :discogs_schema
end

而且,您的所有模型都继承自各自的架构:

And, all your models inherit from the respective schema:

class MyModelFromPublic < PublicSchema
  set_table_name :my_table_name
end

class MyOtherModelFromDiscoGs < DiscoGsSchema
  set_table_name :disco
end

希望能帮到你.

这篇关于在 Rails 模型中使用多个 PostgreSQL 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆