before_filter in few controllers

102 views Asked by At

I would like use one before_filter named :realtor_suscriber in few specific actions in the following controllers :

realtors/registrations_controller.rb
realtors/sessons_controller.rb
pro/messages_controller.rb
pro/users_controller.rb

I defined realtor_suscriber like that in realtors/registrations_controller.rb

def realtor_suscriber!
....my code here...
end

Of course, it doesnt work with action in other controllers (for example pro/messages_controller.rb)

I dont want define realtor_suscriber in application_controller.rb because i've some other controllers they doesnt need this before_filter and i would like avoid to use skip_before_filter in all the other controllers.

Thanks for advance,

F.

4

There are 4 answers

1
Anton Tsapov On BEST ANSWER

You can define the realtor_suscriber! method in ApplicationController and add

before_filter :realtor_suscriber!

in those controllers, where you need it.

3
Satya Kalluri On

You could define it in the application controller skipping specific controllers

def realtor_suscriber!
  if (params[:controller]=="posts" && %w(new edit show).include?(params[:action])) ||
     (params[:controller]=="comments" && %w(create update destroy).include?(params[:action])) ||
     (params[:controller]=="reviews" && %w(like share tweet).include?(params[:action]))
  return # list out all the controller/action pairs which needs to be skipped.
  #....your code here...
end
0
Salil On

Use following

before_filter :realtor_suscriber!, :only => [:abc, :pqr]
#Where abc, pqr are the methods for which you want filter

OR

before_filter :realtor_suscriber!, :except => [:xyz, :rst]
#Where xyz, rst are the methods for which you don't want filter
1
Billy Chan On

This is very simple, just define the method in ApplicationController and use it as filter in sub controllers.

Sub controllers inherits from ApplicationController so they always have access to this method. And you don't need to define such filter in ApplicationController.