Rails before_filter for specific actions in controller

Mau Ruiz picture Mau Ruiz · Apr 8, 2012 · Viewed 27.4k times · Source
  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.

Answer

Hauleth picture Hauleth · Apr 8, 2012

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]