2011-08-20 112 views
3

Section 10.2.1 Rails教程使用before_filter已棄用。在UsersController中編寫代碼以便不使用before_filter的現代慣用方法是什麼?Rails教程:before_filter已棄用

這裏是edit一個版本,我想:

def edit 
    if (signed_in?) 
     @title = "Edit user" 
    else 
     deny_access 
    end 
    end 

然而,這會觸發2次失敗時,我跑rspec的。

rspec ./spec/requests/friendly_forwardings_spec.rb:6 # FriendlyForwardings should forward to the requested page after signin 
rspec ./spec/controllers/users_controller_spec.rb:266 # UsersController authentication of edit/update pages for non-signed-in users should deny access to 'edit' 

回答

11

before_filter不會被棄用。您可能會感到困惑,因爲在Rails 3中,定義已經從ActionController::Filters::ClassMethods移動到AbstractController::Callbacks,但它仍然非常活躍並且非常活躍。

這被定義,棄用免費,在Rails的3.1:
https://github.com/rails/rails/blob/v3.1.0.rc6/actionpack/lib/abstract_controller/callbacks.rb#L80

+0

啊哈,你說得對。謝謝!我仍然對上面發佈的'edit'版本感到好奇。任何想法爲什麼這不等同於使用'before_filter'? – dharmatech

+0

很難說沒有看到測試 – numbers1311407

+0

爲了完整起見,我在下面發佈了非'before_filter'版本。再次感謝您的幫助! – dharmatech

1

這裏是edit不依賴於before_filter版本,並允許規範通:

def edit 
    if (current_user) 
     @user = User.find(params[:id]) 
     if (current_user?(@user)) 
     @title = "Edit user" 
     else 
     redirect_to(root_path) 
     end 
    else 
     session[:return_to] = request.fullpath 
     redirect_to("/signin" , :notice => "Please sign in to access this page.") 
    end 
    end 

我在問題中張貼的原始內容沒有合併correct_user

1

這個答案只是指出了最近的正確解決方案。

before_filter被棄用的Rails 4.2,從release notes

的* _filter的方法家族已經從 文檔中刪除。它們的用法是不鼓勵有利於* _action 家庭的方法:

有一個類似的問題:Rails 4: before_filter vs. before_action

+1

現在沒有折舊:「這些方法將來會被棄用,最終會從Rails中刪除。」 – webster

+0

@rahulv你是對的。 –

+0

5中不推薦使用,將在5.1中刪除https://github.com/rails/rails/commit/7644a99 – tgf

1

Rails CallBacks - ActionController::Basebefore_action只是before_filter的新語法。

然而,在Rails的5.0所有before_filtersare deprecated,將在Rails的5.1

被刪除它只是一個名稱的改變。 before_action更具體,因爲它在動作之前被執行。