我使用devise插件,並有current_user
幫手。我的用戶可以在應用程序中擁有多個配置文件,因此用戶有has_many :profiles
,並且其中一個配置文件始終處於活動狀態。創建current_something幫手
如何以及在哪裏可以創建幫手current_profile
?
問候
我使用devise插件,並有current_user
幫手。我的用戶可以在應用程序中擁有多個配置文件,因此用戶有has_many :profiles
,並且其中一個配置文件始終處於活動狀態。創建current_something幫手
如何以及在哪裏可以創建幫手current_profile
?
問候
可以在ApplicationController
創建幫助,這將使其可用於從繼承的所有控制器和視圖:
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_profile
private
def current_profile
# get current_profile based on current_user here
end
end
現在,你可以在任何的意見/控制器使用current_profile
。
至於如何,真的只是找出哪個配置文件是活動的(我假設一個用戶在一個給定的會話中只能有1個活動配置文件 - 這將使它更容易)。所以,你所做的就是使用你的會話信息找出當前用戶,然後找到活動的個人資料,賓果 - 你就完成了。
只要在哪裏,這是一個真正的範圍問題。如果你想讓輔助方法可用於任何視圖,只需在應用程序控制器中聲明它,並且你應該很好。
在User
類我想補充的方法
class User
has_many :profiles
def current_profile
@current_profile ||= profiles.where('current = ?', true).first
end
end
,然後你的控制器/助手裏面你可以這樣寫:
current_user.current_profile
希望這有助於。