在我的應用程序中,用戶可以屬於許多公司,公司可能有很多用戶,一個用戶可以在兩個或更多公司中操作,在公司中可以有不同的角色,例如公司1用戶可能是管理員,公司2可能是祕書。我創建模型公司用戶和角色如何使用rails製作授權系統?
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
然後我創建模型UsersCompany UsersRole
用戶s_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
,並加入到users_roles數據庫列COMPANY_ID,以確定該公司爲用戶,但是當我更新的用戶模型中添加或刪除角色,COMPANY_ID欄會空值。我認爲這是一個糟糕的主意,而且這個問題有一個正確的解決方案。
這在我的意見
<%= 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 %>
和用戶控制器更新動作
def update
@company = Company.find(params[:company_id])
@user = User.find(params[:id])
redirect_to :back if @user.update
end
如何建立授權制度,如果在同一時間,用戶可以在兩個不同的公司有不同的角色工作?