2015-02-04 49 views
-3

我有一個配置文件控制器,允許用戶訪問他們自己的配置文件,但不允許其他用戶配置文件。在rails中重定向用戶

當我訪問的網址如:http://localhost:3000/en/profiles/2。如果網址對應於不公開個人資料,我希望我的用戶被重定向到他們自己的個人資料。我如何處理這個問題?在我的配置控制器

我的實際行動展示看起來像:

def show 
    @profile = Profile.find(params[:id]) 
    @user = current_user 
    @profile = @user.profile 
    end 

我已經嘗試這種方法,但不起作用

def correct_user 
    redirect_to(profile_path) unless current_user == (@profile.user if @profile) 
    end 
+0

請詳細提供您的問題,以便其他人可以確切地瞭解您在尋找什麼。 請提一下,你想要達到什麼目標,你面臨的問題是什麼,你到現在爲止做了什麼,如果可能的話提供示例代碼。 不要忘記標記相關技術,以便將問題傳達給合適的人。 –

回答

2

你應該邏輯可能會轉移到before_action

before_action :find_profile, :enforce_current_profile 

def show 
end 

protected 

def find_profile 
    @profile = Profile.find(params[:id]) 
end 

def enforce_current_profile 
    unless @profile && @profile.user == current_user 
    redirect_to(profile_path) 
    end 
end 

但是,你真正想做的事情,就是到配置文件控制器轉換爲resource,而不是在你的路線文件resources

resource :profile 

這樣,Rails會產生

GET /profile 

而不是

GET /profile/2 

,你將不再需要任何控制。只需設置

def show 
    @user = current_user 
    @profile = @user.profile 
end 

使用的resource代替resources將不提供index動作,但我懷疑你需要它。

+0

這會引發此錯誤無法找到沒有ID的配置文件find find_profile @profile = Profile.find(params [:id]) end – userails

+0

如果使用'resource',那麼您沒有任何id。你需要相應地調整你的代碼。我假設你有用戶,你已經知道他的個人資料ID。 –

+0

我只是使用你在我的個人資料控制器中給我建議的,但我得到這個錯誤無法找到配置文件沒有ID爲def find_profile @profile = Profile.find(params [:id])結束我的路線爲控制器是資源:配置文件 – userails