【问题标题】:conditionally apply skip_before_filter with :if => condition in rails 4在rails 4中有条件地应用带有:if =>条件的skip_before_filter
【发布时间】:2013-10-13 13:22:38
【问题描述】:

我有一个 Events 控制器,如果事件是公开的,我想在其上跳过身份验证。

在我的ApplicationController 我有这个电话给设计的authenticate_user!

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
end

现在,在我的事件表中,我有一个名为 public 的布尔字段。我用它来检查事件是否公开。像这样在EventsController

class EventsController < ApplicationController
  skip_before_action :authenticate_user!, only: :show, if: Proc.new { :is_public? }
end

但由于某种原因,这不起作用。所以我不得不这样做:

class EventsController < ApplicationController
  skip_before_action :authenticate_user!, only: :show
  before_action :authenticate_user!, unless: :is_public?

  def is_public?
    @event.present? && @event.is_public
  end
end

如果@event.public = true,这将按预期工作并跳过身份验证,因为上面在跳过后以相反的条件重复before_filter

我想知道:

  1. 我做的对吗?
  2. 这对性能有影响吗?如果是,那么有没有更好的方法?

【问题讨论】:

  • 第二段代码,你是不是故意忘记了问号? Proc.new { :is_public }
  • 不。我实际上无法让这个:if =&gt; conditonal 工作,所以不确定它应该是:is_pulic? 还是:is_public
  • 如果你有一个public 字段,它可以是publicpublic?。如果您想使用 is_public? 方法,请将其移至您的 Event 模型。

标签: ruby-on-rails devise ruby-on-rails-4


【解决方案1】:

关于回调(之前、之后、前后)的 Rails 文档实际上非常糟糕。看到这个类似的问题:skip_before_filter ignores conditionals

所以我总是参考 Rails 指南。你感兴趣的部分在这里:http://guides.rubyonrails.org/action_controller_overview.html#other-ways-to-use-filters

我不完全确定这是否也适用于跳过过滤器,但值得一试。

不应该仅仅通过调用不同的过滤器来影响性能。性能问题通常来自大量的数据库查询或其他外部系统调用。

我主要担心的是很难理解为什么会有这么多 before_action 事情发生......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-23
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 2015-08-24
    • 2023-04-04
    • 2018-02-09
    相关资源
    最近更新 更多