In my app users can belongs to many companies, companies may have many users, one user can operate in two or more companies, in company can have different roles, for example in company 1 user maybe administrator and in company 2 maybe secretary. I create models Company User and Role
Company.rb
class Company < ActiveRecord::Base
has_many :users_companies
has_many :users, through: :users_companies
end
User.rb
class User < ActiveRecord::Base
has_many :companies, through: :users_companies
has_many :users_companies
has_many :users_roles, dependent: :destroy
has_many :roles, through: :users_roles
end
Role.rb
class Role < ActiveRecord::Base
has_many :users_roles
has_many :users, through: :users_roles
end
then i create models UsersCompany UsersRole
users_role.rb
class UsersRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
#belongs_to :company
end
Users_role.rb
class UsersRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
#belongs_to :company
end
And add to users_roles db column company_id to determine the company for the user but when i update user model to add or remove role, company_id column will be null. I think its a bad idea and there is a correct solution to this problem.
This in my views
<%= form_for([@company, @user]) do |f| %>
<%= f.label :last_name %><br />
<%= f.text_field :last_name %>
<%= f.label :first_name %><br />
<%= f.text_field :first_name, type: "text" %>
<%= f.label :middle_name %><br />
<%= f.text_field :middle_name, type: "text" %>
<%= hidden_field_tag "user[role_ids][]", nil %>
<% Role.all.each do |role| %>
<%= check_box_tag "user[role_ids][]", role.id, @user.role_ids.include?(role.id), id: dom_id(role) %>
<%= label_tag dom_id(role), role.second_name %><br>
<% end %>
<%= f.submit, class: "login loginmodal-submit", type: "submit" %>
<% end %>
and users controller update action
def update
@company = Company.find(params[:company_id])
@user = User.find(params[:id])
redirect_to :back if @user.update
end
how to build a system of authorization if the user at the same time can work in two different companies with different roles?