Joh*_*han 64 postgresql ruby-on-rails schema-design models database-schema
我的Rails应用程序有一个PostgreSQL数据库.在名为"public"的模式中,存储了主Rails模型表等.我创建了一个"discogs"模式,其中的表名称有时与"public"模式中的名称相同 - 这是其中一个原因.我正在使用模式来组织这个.
如何从我的应用程序中的"discogs"架构设置模型?我将使用太阳黑子让Solr为这些模型编制索引.我不确定你会怎么做.
小智 101
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"
Run Code Online (Sandbox Code Playgroud)
或者,您可以为每个架构指定不同的连接:
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"
Run Code Online (Sandbox Code Playgroud)
定义每个连接后,创建两个模型:
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
Run Code Online (Sandbox Code Playgroud)
并且,所有模型都继承自相应的模式:
class MyModelFromPublic < PublicSchema
set_table_name :my_table_name
end
class MyOtherModelFromDiscoGs < DiscoGsSchema
set_table_name :disco
end
Run Code Online (Sandbox Code Playgroud)
我希望它有所帮助.
Lal*_*alu 12
rails 4.2的正确版本如下:
class Foo < ActiveRecord::Base
self.table_name = 'myschema.foo'
end
Run Code Online (Sandbox Code Playgroud)
更多信息 - http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name-3D
man*_*iek 10
做就是了
class Foo < ActiveRecord::Base
self.table_name = 'myschema.foo'
end
Run Code Online (Sandbox Code Playgroud)
因为set_table_name
被删除了,它被替换了self.table_name
.
我认为你应该编码如下:
class Foo < ActiveRecord::Base
self.table_name = 'myschema.foo'
end
Run Code Online (Sandbox Code Playgroud)
在迁移中:
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
Run Code Online (Sandbox Code Playgroud)
在模型中可选
class User < ActiveRecord::Base
self.table_name 'settings.users'
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21437 次 |
最近记录: |