Rails教程:不推荐使用before_filter

时间:2011-08-20 03:00:25

标签: ruby-on-rails ruby-on-rails-3 railstutorial.org

Rails教程的

Section 10.2.1使用了不推荐使用的before_filter。在UsersController中编写代码以便不使用before_filter的现代惯用方式是什么?

这是我尝试的edit版本:

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

但是,这会在我运行rspec时触发2次失败。

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'

4 个答案:

答案 0 :(得分:11)

不推荐使用

before_filter。您可能会感到困惑,因为定义在Rails 3中从AbstractController::Callbacks移到了ActionController::Filters::ClassMethods,但它仍然非常活跃和踢。

这里是Rails 3.1中定义的,不含引用的:
https://github.com/rails/rails/blob/v3.1.0.rc6/actionpack/lib/abstract_controller/callbacks.rb#L80

答案 1 :(得分: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

答案 2 :(得分:1)

这个答案只是为了指出正确的解决方案。

release notes

的Rails 4.2中不推荐使用

before_filter

  

* _filter系列方法已被删除   文档。不鼓励使用它们以支持* _action   方法家族:

有一个类似的问题:Rails 4: before_filter vs. before_action

答案 3 :(得分:1)

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

但是,Rails 5.0中的所有before_filters are deprecated都将在Rails 5.1中删除

这只是一个名称变更。 before_action更具体,因为它在行动之前执行。

相关问题