加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 为什么当控制器被子类化时,Rails before_filte

发布时间:2020-12-16 19:41:43 所属栏目:百科 来源:网络整理
导读:我在Rails 2.3.5,我有这个问题: class BaseController ApplicationController before_filter :foo,:only = [:index]endclass ChildController BaseController before_filter :foo,:only = [:index,:show,:other,:actions]end 问题是在ChildController上,foo
我在Rails 2.3.5,我有这个问题:
class BaseController < ApplicationController
  before_filter :foo,:only => [:index]
end

class ChildController < BaseController
  before_filter :foo,:only => [:index,:show,:other,:actions]
end

问题是在ChildController上,foo before filter被调用两次.

我已经尝试了许多解决这个问题的解决方法.如果我没有在子代码中包含:index操作,它将永远不会被调用.

我找到的解决方案是有用的,但我认为这非常非常丑陋

skip_before_filter :foo
before_filter :foo,:actions]

有没有更好的方法来解决这个问题?

解决方法

“此行为是设计使然”.

控制器上的Rails指南说明:

“过滤器是继承的,所以如果在ApplicationController上设置过滤器,它将在应用程序中的每个控制器上运行.

这解释了你所看到的行为.它还建议您提出的完全相同的解决方案(使用skip_before_filter)来定义特定控制器和/或方法将要执行哪些过滤器或不运行哪些过滤器.

那么,丑陋还是不好,似乎你发现的解决方案是常见和批准的做法.

http://guides.rubyonrails.org/action_controller_overview.html#filters

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读