Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails before_filter for specific actions in controller

  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.

like image 635
Mau Ruiz Avatar asked Apr 08 '12 08:04

Mau Ruiz


People also ask

What is action controller Rails?

Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed on request and then either it renders a template or redirects to another action.

What are controller callbacks in Rails?

Rails provides before and after actions in controllers as an easy way to call methods before or after executing controller actions as response to route requests.

What does before action do in Rails?

The only option of before_action defines one action OR a list of actions when the method/block will be executed first. The set_newsletter_email method will be called just before the show and edit actions. The opposite option except define when NOT to execute the method/block.

What is params in Ruby on Rails?

With params . Inside your controller action's you can call params to access form & URL query data. What is params , exactly? It's a method that returns an ActionController::Parameters object, in practice it behaves a lot like a hash.


1 Answers

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] 
like image 115
Hauleth Avatar answered Sep 22 '22 13:09

Hauleth