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

查看:78
本文介绍了在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天全站免登陆