I've built a multi-tenancy app that has User
& Report
that belong to a Company
as shown below, (multi tenancy app using company_id to scope everything else - Users & Reports).
company.rb
class Company < ApplicationRecord
has_many :reports
has_many :users
end
user.rb
class User < ApplicationRecord
belongs_to :company
has_many :reports
end
report.rb
class Report < ApplicationRecord
belongs_to :user
belongs_to :company
end
I now wish to add an Agency
model (with agency_users
) that will enable the to manage multiple companies (and that companies reports). The Agent will need to be able to switching from one company two another.
How would I approach this? Agent has many Companies
class Agent < ApplicationRecord
has_many :companies
end
I can't quite work out how the agent would switch between the company_ids in order to view the reports for the companies it is responsible (it's clients).
Based on the comment, here's a solution that can be helpful
class Agency < ApplicationRecord
has_many :companies
has_many :users
end
class Company < ApplicationRecord
has_many :reports
belongs_to :agency
end
class Users < ApplicationRecord
has_many :reports
belongs_to :agency
enum role: [:agent]
end
Now, when the user signs in to your app, show him a dropdown of which company he's currently controlling. Store this id
in a session and use it to query your data:
current_user.reports.where(company_id: session[:company_id].to_i)
for example;
Same goes to creating and deleting them.
However, this is not the optimal solution (I'm not sure what your intentions are).
I would go with something more general, like user roles for each company with UserCompany
having company
, user
and role
instead of the role
on the user level (maybe he's an agent at a company but admin another company; etc...). All of that varies based on what you really need to do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.