我有一個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
與逆條件認證。
我很納悶:
- 我所做的是正確的?
- 這是否有任何性能影響。如果是,那麼有更好的方法嗎?
在代碼的第二塊,你忘了有目的的問號? 'Proc.new {:is_public}' – Damien
沒有。我實際上無法得到這個':if => conditonal'來工作,所以不知道它應該是':is_pulic?'還是':is_public' – CuriousMind
如果你有一個'public'字段,它可以是'公共「還是」公共?「。如果你想使用它,請將'is_public?'方法移到你的'Event'模型中。 – Damien