2017-03-31 79 views
-1

我目前正在使用RoR構建類似自由職業者的網站,但我被卡住了某處,用設計生成的我的用戶表具有可以是管理員,客戶端或自由職業者。此外,我有一個屬於用戶的技能表,但我不希望每個用戶都具有技能,除了具有自由職業者角色的用戶,我如何去做這件事,目前我正在使用cancancan進行用戶授權和設計認證,是角色這樣或STI的最佳解決方案,以及如何將你建議我解決這個問題,這裏是一個示例代碼單個用戶角色的Rails關係

class User < ApplicationRecord 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    has_many :user_roles 
    has_many :skills 
    has_many :skills, through: :user_skills ## I don't want all users to have skills except the users with the role of freelancer 
    has_many :roles, through: :user_roles 

    def role?(role) 
    roles.any? { |r| r.name.underscore.to_sym == role } 
    end 

end 

謝謝你在期待中。

+0

對不起,但爲什麼這個問題投下了票? – Wigo

+0

您需要補充您的問題,請參閱[MCVE](http://stackoverflow.com/help/mcve)幫助。 –

+0

請顯示您已經寫過的代碼。你卡在哪裏?你面對什麼問題? – spickermann

回答

0

你可以做這樣的事情:

class Skill < ApplicationRecord 
    belongs_to :user, -> { where role: 'freelancer' } 
end 

請記住,這將節省skills任何role,但他們只爲freelancer可見。 您也可以使用cancancan來檢查用戶是否是自由職業者。