Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

ruby on rails - Accessing data from two or more schemas in a multi tenant application

We are using apartment gem for multi-tenant application. For each account, there will be a separate schema is maintained. based on the subdomain of the account, we list the data in each account.

In our new requirement, there is something like a super account where all the account data can be viewed. For example, if account 1 and account 2 is selected in the user list page, users of account 1 and 2 should be combined and viewed along with search provision. Is there any way to combine more than one schema data in the apartment? or any other alternates


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The simplest approach I can think of is to perform union queries across the relevant schemas. So if you have schemas account_1 and account_2, you'd do something like SELECT * FROM account_1.users UNION SELECT * FROM account_2.users.

You can, of course, make this dynamic –?so if you send the affected accounts as part of the params hash, you'd potentially have something like this:

accounts = Account.find(params[:account_ids])
# assuming the schema name is stored in the accounts.tenant_name column:
sql = accounts.map { |account| "SELECT * FROM #{account.tenant_name}.users" }.join(" UNION ")
users = User.find_by_sql(sql)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...