1

也称为<<“用户有很多数据库”问题。>>

环境

我的应用程序是这样建模的:

user has_many databases  
database has_many tables  
table has_many rows  
row habtm(+value) columns   

你明白了!

因此,我不想在数据库中建模数据库,而是希望:

  • 一个保存用户的 sqlite3 数据库和
  • 每个用户有许多 sqlite 数据库

每个用户都会在他的数据库中 LCRUD 他的表(类似于 phpmyadmin)

问题

我想为数据库连接和 table_name 进行线程安全的每个请求配置

class Table < ActiveRecord::Base
end

# in some controller
# set the connection to the user-selected database from some DB list
Table.connection = current_user.session.connection
# set the name to the user-selected table from some tables list
Table.table_name = params[:table_name]
@rows = Table.all #display them

编辑
如您所见,连接是全局的并且在线程之间共享,但根据我的应用程序规范,每个用户都有自己的连接。现在假设 2 个不同的用户同时发出 2 个请求。

选项?

  • 我放弃 ActiveRecord 并使用准系统 DB 驱动程序
  • 我放弃线程安全
4

2 回答 2

4

我相信这就是咒语:
用于Class.new(AR::Base)动态创建类

post_class = Class.new(ActiveRecord::Base)
post_class.connection = set_up_connection()
post_class.table_name = :posts

@posts = post_class.all
puts @posts

# note: post_class will get GC'ed at scope end just like any var, sweet!
于 2010-09-25T07:07:10.107 回答
0

Rails 通常为每个请求设置一个进程,以便每个 http 请求都由它自己的进程处理。为允许该功能的 apache 模块查找乘客

在这样的配置中不需要线程安全,事实上活动记录不是完全安全的 afaik

于 2010-09-22T16:32:40.220 回答