2011-07-08 59 views
2

我正在慢慢地學習rails的做和測試的事情,但我遇到了一個塊。我有一個簡單的rails 3.1應用程序,並有一個簡單的用戶註冊/登錄過程中的工作。我不使用設計,因爲我寧願學習如何自己做。Rails 3.1只有用戶可以編輯他們的配置文件

當前用戶可以註冊,登錄和註銷。但我希望他們能夠編輯他們的個人資料。目前任何用戶都可以轉到users/1/edit /即使他們的ID未設置爲1.如何檢查current_user是否與url相匹配?我知道我需要某種在我的users_controller的編輯動作過濾之前。

這裏是我目前

users_controller.rb

before_filter :is_owner, :only => [:edit, :update, :destroy] 

application_controller.rb

helper_method :is_owner 
def is_owner 
end 

應該是什麼在我的is_owner功能?

回答

3

我猜你的問題在於從URL獲取參數。這可能與參數數組來完成:

params[:id] 

隨着那(取決於你的路由配置!),你可以不喜歡

def is_owner? 
    current_user.id == params[:id] 
end 
2

Fuzzyalej顯然是一個比我快打字員;-) ,所以我只能建議你一些更詳細的函數形式。 (他的回答是絕對正確的)

您已經在ApplicationController中定義了過濾器方法,但在這種情況下,僅比較'id'參數可能會引起誤解,因爲在其他操作中,'id'可能描述文檔(例如)而不是用戶。 如果你在UsersController中定義了過濾器函數可能會更安全(只是把它設爲一個私有函數)

就我個人而言,我經常在動作中直接放置類似的規則,但使用過濾器可能會更幹。

我所界定的方法「編輯」,「更新」,以這種方式「摧毀」:(也許你會喜歡它)

def edit # and 'update', and 'destroy' 
    @user = User.find(params[:id]) 
    render_forbidden and return unless can_edit? 
    # ...and the rest of the action 
end 

private 

def can_edit? 
    current_user.is_admin? || current_user == @user 
end 

# This one usually is defined in ApplicationController, as I use it often 
def render_forbidden 
    respond_to do |format| 
    format.html { render :action => "errors/forbidden", :status => 403 } 
    #... 
    end 
    true 
end 
相關問題