2015-09-26 26 views
0

在我的應用程序中,用戶可以屬於許多公司,公司可能有很多用戶,一個用戶可以在兩個或更多公司中操作,在公司中可以有不同的角色,例如公司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 

如何建立授權制度,如果在同一時間,用戶可以在兩個不同的公司有不同的角色工作?

回答

0

我不知道爲什麼,當你更新的作用,在COMPANY_ID成爲空,但在你的概念模型,用戶可以在同一個公司的許多角色,我認爲這是錯誤的。此外,似乎公司用戶(這是公司和用戶之間的基本關係)似乎不需要對user_role做任何事情,這使得更新和追蹤哪個用戶在哪個公司中具有哪個角色。

我想建議那些類模型,以獲得用戶,角色和公司之間的關係。

class User 
    has_many :user_roles 
    has_many :companies, through: :user_roles 
end 

class Company 
    has_many :user_roles 
    has_many :users, through: :user_roles 
end 

class UserRole 
    belongs_to :user 
    belongs_to :company 
    belongs_to :role 
end 

class Role 
    has_many :user_roles 
end 

我想你知道如何處理遷移。