【问题标题】:Multiple database schemas in Rails 3 and MySQLRails 3 和 MySQL 中的多个数据库模式
【发布时间】:2011-06-17 04:02:14
【问题描述】:

在 Rails 3 中是否可以为 ActiveRecord 模型指定不同的模式?以下曾经在 Rails 2 中工作:

class Company < ActiveRecord::Base
  set_table_name "hr.company"
end

这在 Rails 3 中失败并显示消息 Table myapp.hr.company doesn't exist

以下适用于简单模型:

class Company < ActiveRecord::Base
  establish_connection "hr"
  set_table_name "company"
end

这种方法的问题是双重的:首先,Rails 为这个模型创建了一个单独的数据库连接,增加了额外的开销。其次,现在所有查询都在此连接的上下文中调用,这意味着任何返回到 myapp 架构的连接都将中断:

class Company < ActiveRecord::Base
  establish_connection "hr"
  set_table_name "company"
  has_many :widgets # widgets table resides in myapp schema
end

这反过来会以Table hr.widgets doesn't exist 失败。

那么,有什么方法可以在 Rails 3 中实现这一点吗?

【问题讨论】:

  • 澄清一下……您是要临时更改表名还是永久更改表名?
  • 永久,如中,限定的表名应始终用于此模型。

标签: mysql ruby-on-rails ruby-on-rails-3


【解决方案1】:

你可以使用抽象类并继承它:

app/models/db.rb

class Db < ActiveRecord::Base
  establish_connection :db
  self.abstract_class = true
end

app/models/post.rb

class Post < Db
  set_table_name :notes
  belongs_to :user
end

app/models/user.rb

class User < ActiveRecord::Base
  has_many :posts
end

config/database.yml

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000


db:
  adapter: sqlite3
  database: db/db.sqlite3
  pool: 5
  timeout: 5000

在 db.sqlite3 中只有notes 表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2011-07-13
    • 2010-12-22
    相关资源
    最近更新 更多