[英]Can I have thread safe per-request configuration for database connection and table_name in ActiveRecord (or Mongoid)?
又稱<<“用戶有很多數據庫”的問題。>>
環境
我的應用程序建模如下:
user has_many databases
database has_many tables
table has_many rows
row habtm(+value) columns
你明白了!
因此,我不想在數據庫內建模數據庫,而是希望:
每個用戶都會在他的數據庫中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個請求。
選項?
我相信這是咒語:
使用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模塊的乘客
在這樣的配置中,不需要線程安全,事實上活動記錄不完全是安全的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.