2017-05-30 45 views
-1

我有一個使用devise進行身份驗證的用戶模型。我也有一個用戶信息(學生)模型和僱主模型。僱主和用戶信息都使用註冊模型註冊。然後他們選擇「繼續作爲僱主或學生」。如何讓某些模型的用戶瀏覽一個頁面,而其他的則限制在rails應用中?

  1. 如果他們繼續作爲學生,他們會被要求填寫一些信息。 的信息每個學生填寫將會展示給他們在用戶 資料頁「用戶信息#秀」所有的學生。信息會顯示在 ‘用戶信息#指數’頁面。
  2. 當然,如果他們繼續僱主,他們必須填補一些不同 信息適用於他們。他們的信息只顯示在他們的 的個人資料頁「的僱主#秀」。

如果我只希望僱主看到「用戶信息#指數」頁面,我該怎麼做?這意味着,如果您以學生身份註冊,您只能看到您的個人資料(userinfo#show),並且無法看到「userinfo#index」。僱主可以看到userinfo#index a nd 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 

USERINFO型號:

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 

我的遷移:

  1. devise_create_users.rb
  2. create_userinfos.rb
  3. add_user_id_to_userinfos.rb
  4. create_employers.rb
  5. add_user_id_to_employers.rb

即使它這裏沒有顯示,我在每個模型的獨特功能檢查是否在用戶信息模型中輸入了學生信息,以及是否在僱主模型中輸入了僱主信息。我有他們,因爲當用戶註冊時,程序檢查學生信息或僱主信息是否已經輸入,如果是,他們不必選擇「僱主或學生」。因爲他們已經選擇了。我的問題是,我不能使用這兩個功能來檢查他們是僱主還是學生?就像,如果學生信息已經填好,他們是學生,所以他們不會被允許看到索引頁。我只是不知道如何實現它。

+0

要明確一點,'僱主'模型有關於用戶的信息,只有在用戶是僱主時纔會被填寫。這些名稱聽起來像'僱主'有關於用戶的僱主的信息。另外,在用戶的應用程序中是否有可能同時擁有「僱主」和「用戶信息」? – Max

+0

@Max Hey Max!是的,第一個問題。只有當這個人是僱主時,僱主模型信息纔會被填寫。不,用戶不能同時擁有userinfo和僱主。它的設置方式是,只要用戶註冊,程序就會檢查用戶信息模型或僱主模型是否填寫完畢。如果沒有填寫,用戶會被路由到一個頁面,他們必須選擇他們是僱主還是學生(用戶信息)。由於他們選擇後不能更改,用戶只能擁有僱主或用戶信息。 – Dinukaperera

+0

您可否使用Devise提供的[authenticate_user!](https://github.com/plataformatec/devise#controller-filters-and-helpers)helper? –

回答

1

所以我會做兩件事。首先對模型:

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 

一個長期的解決方案,如果您有不同的角色就可以考慮使用角色管理的寶石一樣權威人士或cancancan之一。對於短期簡單的項目,此解決方案將起作用。

1

將角色添加到用戶模型可以解決此問題。我建議使用rails的枚舉功能並添加僱主/學生角色,然後在應用程序控制器中編寫一個輔助方法,以在顯示頁面之前檢查當前用戶是僱主/學生。

+0

嘿,賴利,請檢查我的問題的最後一部分。我最近添加了它。 – Dinukaperera

相關問題