我可以有线程安全的每个请求的配置数据库连接和TABLE_NAME的ActiveRecord的(或Mongoid)? [英] Can I have thread safe per-request configuration for database connection and table_name in ActiveRecord (or Mongoid)?
问题描述
也叫的<<用户有很多数据库的问题>>
Also known as the <<"User has many Databases" question.>>
环境
我的应用程序是模仿像这样:
My app is modeled like so:
user has_many databases
database has_many tables
table has_many rows
row habtm(+value) columns
你的想法!
you get the idea!
因此,而不是模拟数据库的在的数据库, 我想有:
So instead of modelling a database inside a database, I would like to have:
- 保存用户和sqlite3的数据库
- 在每个用户的许多SQLite数据库
每个用户LCRUD他在他的数据库中的表(类似于phpMyAdmin的)
Each user will LCRUD his tables in his databases (similar to phpmyadmin)
问题
我想有线程安全的的每个请求的配置 数据库连接和TABLE_NAME
I would like to have thread safe per-request configuration for database connection and 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请求。
EDIT
As you see, the connection is global and shared between threads, but as per my app's specs, each user has it's own connection. Now imagine that 2 different users make 2 requests at the same time.
的选项?
- 在我放弃的ActiveRecord和使用裸机DB驱动程序
- 在我放弃线程saftey
推荐答案
我相信这是咒语:
使用 Class.new(AR :: Base的)
来动态地创建类
I believe this is the incantation:
Use Class.new(AR::Base)
to dynamically create classes
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!
这篇关于我可以有线程安全的每个请求的配置数据库连接和TABLE_NAME的ActiveRecord的(或Mongoid)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!