3

Rails 教程的第 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

4 回答 4

11

before_filter没有被弃用。AbstractController::Callbacks您可能会感到困惑,因为该定义是从Rails 3移到的ActionController::Filters::ClassMethods,但它仍然非常活跃和活跃。

在这里,它在 Rails 3.1 中定义,无弃用:
https ://github.com/rails/rails/blob/v3.1.0.rc6/actionpack/lib/abstract_controller/callbacks.rb#L80

于 2011-08-20T03:34:26.517 回答
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.

于 2011-08-20T06:15:55.293 回答
1

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

before_filter在 Rails 4.2 中已弃用,来自发行说明

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

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

于 2015-06-19T10:40:59.483 回答
1

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

但是,所有这些在 Rails 5.0before_filters 中都已弃用,并将在 Rails 5.1 中删除

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

于 2016-03-23T05:44:20.143 回答