75

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

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

4

6 回答 6

114

database.yml 中的 PostgreSQL 适配器 schema_search_path 能解决你的问题吗?

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

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

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"

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

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

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

class MyModelFromPublic < PublicSchema
  set_table_name :my_table_name
end

class MyOtherModelFromDiscoGs < DiscoGsSchema
  set_table_name :disco
end

我希望它有所帮助。

于 2012-01-12T16:50:35.437 回答
18

rails 4.2的正确一个是:

class Foo < ActiveRecord::Base
  self.table_name = 'myschema.foo'
end

更多信息 - http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name-3D

于 2016-03-11T16:53:01.097 回答
13

在迁移中:

class CreateUsers < ActiveRecord::Migration
  def up
    execute 'CREATE SCHEMA settings'
    create_table 'settings.users' do |t|
      t.string :username
      t.string :email
      t.string :password

      t.timestamps null: false
    end
  end

  def down
    drop_table 'settings.users'
    execute 'DROP SCHEMA settings'
  end

end

型号可选

class User < ActiveRecord::Base
  self.table_name 'settings.users'
end
于 2016-05-06T17:10:46.857 回答
11

做就是了

class Foo < ActiveRecord::Base
  self.table_name = 'myschema.foo'
end
于 2012-01-15T15:09:43.210 回答
11

因为set_table_name被删除了,它被替换为self.table_name.

我认为你应该编码如下:

class Foo < ActiveRecord::Base
  self.table_name =  'myschema.foo'
end
于 2016-01-20T02:59:09.630 回答
4

方法set_table_name已被删除。self.table_name工作正常。

于 2015-08-05T10:07:52.053 回答