2013-10-13 26 views
6

我有一個Events控制器,我想在該事件公開時跳過身份驗證。有條件地將skip_before_filter應用於:if => condition in rails 4

在我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. 這是否有任何性能影響。如果是,那麼有更好的方法嗎?
+1

在代碼的第二塊,你忘了有目的的問號? 'Proc.new {:is_public}' – Damien

+0

沒有。我實際上無法得到這個':if => conditonal'來工作,所以不知道它應該是':is_pulic?'還是':is_public' – CuriousMind

+0

如果你有一個'public'字段,它可以是'公共「還是」公共?「。如果你想使用它,請將'is_public?'方法移到你的'Event'模型中。 – Damien

回答

6

有關回調的rails文檔(之前,之後,周圍的動作)實際上很糟糕。看到這個類似的問題:skip_before_filter ignores conditionals

所以我總是指的導軌指南。有趣的部分在這裏:http://guides.rubyonrails.org/action_controller_overview.html#other-ways-to-use-filters

我不完全相信,這將與跳過濾器一起工作,但它是值得一試。

只需調用不同的過濾器就不會影響性能。性能問題通常來自廣泛的數據庫查詢或其他外部系統調用。這裏

我最關心的是,這是相當困難的理解,爲什麼有這麼多的東西before_action回事...