我想讓一個我的ruby on rails Web應用程序的頁面無法訪問我的一個STI模型類型。我有兩個繼承自User的typeA和typeB模型。我在用戶表中使用了列類型來實現STI。我正在使用Devise gem進行用戶會話。我希望我的typeA用戶無法訪問一個網頁'http://localhost:3000/rate'。無論何時用戶登錄「typeA」類型的用戶,他都沒有選擇查看鏈接「費率」的選項。但我也不希望他能通過鏈接「http://localhost:3000/rate」訪問該頁面。如果他試圖通過該鏈接訪問它,我想簽署他並讓他再次登錄。 我通過使用Controller中的一段代碼來處理這個問題,並使用'rate'的具體方法。如何使我的基於STI的設計用戶模型類型之一的某些頁面無法訪問我的Ruby on Rails應用程序?
def rate
if current_user.type == "typeA"
sign_out(current_user)
redirect_to new_user_session_path
else
#Code for User of typeB
end
end
這是工作,但我想知道這是否可以使用的before_filter一種更好的方式來完成:的authenticate_user!或別的東西 現在我的before_filter部分看起來像這樣
before_filter :authenticate_user!, except: [:index, :show]
有什麼辦法,我可以做出改變到上代碼來實現該功能。
P.S:也許這可以做得更好,如果我曾經使用角色或其他像CanCan/Pundit這樣的寶石,但我沒有太多時間提交我的項目,所以我現在不想進入這一切。與您的控制器
class ApplicationController
before_action :authenticate_user!
def authorize_user!
if current_user.type == "typeA"
sign_out(current_user)
redirect_to new_user_session_path
end
end
end
:
我不希望整個控制器無法輸入A。我只想要'rate'頁面無法訪問到他。還有其他的方法,如索引,創建,顯示等,他應該仍然可以訪問它。我如何把它放在我的代碼中? –
你可以使用'only:'選項來做'before_filter {| c | c.confirm_user_type(TypeA)},:only => [:rate]' – sa77
我現在得到的錯誤頁面是/Users/Suvajit/Documents/Code/Rails/Mckenzie/app/controllers/dishes_controller.rb:4:syntax錯誤,意外':',期待keyword_end .confirm_user_type(TypeA)}:only => [:rate]^ 我使用的代碼是 'before_filter {| c | c.confirm_user_type(TypeA)},:only => [:rate]' –