【问题标题】:Rails Tutorial: before_filter deprecatedRails 教程:不推荐使用 before_filter
【发布时间】:2011-10-31 01:20:21
【问题描述】:

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'

【问题讨论】:

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


    【解决方案1】:

    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

    【讨论】:

    • 啊哈,你是对的。谢谢!我仍然对我在上面发布的edit 的版本感到好奇。知道为什么这不等于使用before_filter
    • 不看测试很难说
    • 为了完整起见,我在下面发布了非before_filter 版本。再次感谢您的帮助!
    【解决方案2】:

    这是 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

    【讨论】:

      【解决方案3】:

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

      before_filter 在 Rails 4.2 中被弃用,从 release notes:

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

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

      【讨论】:

      【解决方案4】:

      Rails CallBacks - ActionController::Base, before_action 只是 before_filter 的新语法。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多