![](/img/trans.png)
[英]How to let users backup their posts to Google drive from Rails app?
[英]How to let users from certain model view a page while the rest is restricted in rails app?
我有一個使用devise進行身份驗證的用戶模型。 我也有一個userinfo(學生)模型和一個雇主模型。 雇主和用戶信息都使用注冊模型進行注冊。 然后,他們選擇“繼續作為雇主或學生”。
如果我只希望員工看到“ userinfo#index”頁面,該怎么辦? 這意味着,如果您注冊為學生,則只能看到您的個人資料(userinfo#show),而看不到“ userinfo#index”。 雇主可以看到userinfo#index和userinfo#show。
用戶模型:
class User < ActiveRecord::Base
has_one :userinfo
has_one :employer
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
用戶信息模型:
class Userinfo < ActiveRecord::Base
belongs_to :user
end
def info_complete?
name? && email? && college? && gpa? && major?
end
雇主模式:
class Employer < ActiveRecord::Base
belongs_to :user
end
def info_complete?
name? && company? && position? && number? && email?
end
我的遷移:
即使未在此處顯示,我在每個模型中都有一個獨特的功能來檢查是否已在userinfo模型中輸入了學生信息以及是否已在雇主模型中輸入了雇主信息。 之所以在這里,是因為在用戶注冊時,程序會檢查是否已經輸入了學生信息或雇主信息,如果已經輸入,則不必選擇“雇主或學生”。 因為他們已經選擇了。 我的問題是,我不能使用這兩個功能來檢查它們是雇主還是學生? 像是,如果學生信息已經填寫完畢,他們就是學生,因此將不允許他們查看索引頁面,我只是不知道如何實現它。
在用戶模型中添加角色可以解決此問題。 我建議使用Rails的枚舉功能並添加雇主/學生角色,然后在應用程序控制器中編寫一個輔助方法,以在顯示頁面之前檢查當前用戶是否是雇主/學生。
所以我分兩部分來做。 首先為模型:
class User < ActiveRecord::Base
...
def user_type
return :user if self.userinfo.present?
return :employer if self.employer.present?
return :no_role
end
end
接下來是控制器:
def index
if current_user.user_type == :no_role
redirect_to select_role_path, notice: "Please select your role before continuing"
return
elsif current_user.user_type == :user
redirect_to some_safe_path, notice: "You do not have permission to view this page"
return
end
... continue with the normal code here
end
對於長期解決方案,如果您要擔任不同的角色,請考慮研究一下諸如pundit或cancancan之類的角色管理寶庫。 對於短期的簡單項目,此解決方案將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.