Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an inherited controller add to parent's before_action conditions

class ParentController < ApplicationController
  before_action admin_user, only: [:create, :update]
end

class ChildController < ParentController
  before_action admin_user #Also want to add :tweet

  def tweet
  end
end

In the ChildController we could use

before_action admin_user, only: [:create, :update, :tweet]

but then if I change anything in the parent's before_action, it won't get updated in the child.

like image 537
gitb Avatar asked Jul 13 '17 20:07

gitb


2 Answers

You could call the method inside of a block inside ChildController instead of passing it by name. That would look like this:

class ParentController < ApplicationController
  before_action admin_user, only: [:create, :update]
end

class ChildController < ParentController
  before_action(only: [:tweet]) { admin_user }

  def tweet
  end
end
like image 78
yeslad Avatar answered Oct 25 '22 02:10

yeslad


Unfortunately, the way ActiveSupport::Callbacks is implemented does not allow an additional action to be easily added to the configuration of the before filter. You could do this though:

class ParentController < ApplicationController
  AdminActions = [:create, :update]
  before_action :admin_user, only: AdminActions
end

class ChildController < ParentController
  before_action :admin_user, only: superclass::AdminActions + [:tweet]
end
like image 36
Mate Solymosi Avatar answered Oct 25 '22 02:10

Mate Solymosi