Alaa Othman
Alaa Othman

Reputation: 1149

Pass parameter to callback in the controller

I have these two methods in my application controller what i want is to use them as callbacks in my projects_controller like this but it gives me error, can anyone tell me how to fix this.

before_action :permit_show(@project), only:[:show]
before_action :permit_edit(@project), only:[:edit]



def permit_edit(object)
  if (current_user.id != object.creator_id)
   render_404
  end   
end

def permit_show(object)
 members = object.users
 if (!members.include? current_user)
  render_404
 end   
end

Upvotes: 2

Views: 3429

Answers (3)

Dty
Dty

Reputation: 12273

Credit to this so answer.


...you can achieve what you're looking for by using optional method parameters, like so:

def cache_bust(callback = true)
  ... method body
end

In the scenario where the method is called from the after_update callback, the parameter is not passed, but defaults to true. Otherwise, if the method is called from anywhere else "manually", you have the option of passing whatever value you wish to that method.

Upvotes: 1

LHH
LHH

Reputation: 3323

You can use send method to pass parameter something like this -

before_action only: [:show] do |c|
  c.send(:permit_show, @project)
end

before_action only: [:edit] do |c|
   c.send(:permit_edit, @project)
end

Upvotes: 1

Zero Fiber
Zero Fiber

Reputation: 4465

To pass in parameters, you have to use a block.

before_filter(only: [:show]) { permit_show(@project) }
before_filter(only: [:edit]) { permit_edit(@project) }

Upvotes: 6

Related Questions