我可以在ActiveRecord(或Mongoid)中为数据库连接和table_name配置线程安全的每个请求配置吗?
又称<>
环境
我的应用程序是这样建模的:
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个请求。
选项?
- 我放弃了ActiveRecord并使用了裸机数据库驱动程序
- 我放弃线程安全
我相信这是咒语:
使用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!
Rails通常设置为每个请求一个进程,以便每个http请求由其自己的进程处理。 查找允许的apache模块的乘客
在这样的配置中,不需要线程安全,事实上活动记录不完全是安全的
- Rails gem rails3-jquery-autocomplete:如何查询多个字段
- rails – using:select(distinct)with:has_many:通过关联产生无效的SQL
- has_one和has_many在同一个模型中。 铁轨如何跟踪它们?
- 使用end作为列名
- ActiveModel :: SecurePassword未定义方法`password_digest =’
- Rails有活跃记录一次性获取所有需要的关联吗?
- Rails中的高级SQL
- 错误:缺少表“self”的FROM子句条目(Rails 4 Active Record事务,postgresql 9.4))
- 为什么这个Ruby on Rails代码不能像我想要的那样工作?