Rails before_filter for specific actions in controller

旧巷老猫 提交于 2019-11-29 02:15:01

问题


  def new
    before_filter  do 
      redirect_to "/" unless current_admin || current_company
      flash[:notice] = 'You dont have enough permissions to be here' unless current_admin || current_company

     end
    CODE CODE CODE
   end

  def edit
    before_filter  do 
      redirect_to "/" unless current_admin.id = 5
      flash[:notice] = 'You dont have enough permissions to be here' unless current_admin || current_company

     end
    CODE CODE CODE
   end

This is the code that I want to do, but I cant figure out how to do it right. What I want to achieve is to apply a before_filter rule for each of my actions. So perhaps a User can acces de INDEX action but not the EDIT action etc. I know that the before_filter method runs a single time, and I cannot run 4 before_filters, I'm just giving some reference because of my poor english.

You must know that I am using Devise for the current_admin and current_company methods. I need to apply different filters (if admin or if company.id = X) and other actions.

Thanks in advance, I am pretty stucked in here. Any help will be appreciated.


回答1:


Create in your ApplicationController method:

def check_privileges!
  redirect_to "/", notice: 'You dont have enough permissions to be here' unless current_admin || current_company
end

And then in your controller:

before_filter :check_privileges!, only: [:new, :create, :edit, :save]

Or

before_filter :check_privileges!, except: [:index, :show]


来源:https://stackoverflow.com/questions/10061373/rails-before-filter-for-specific-actions-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!