tehAnswer
tehAnswer

Reputation: 1018

Callback and code factoring

I was programming one controller which most of its methods call at the end respond_with method. So an idea comes to my mind "Can I use a callback to don't have to repeat that line more than once?"

Maybe it's some extreme and it's worthless but I need to know that. So I tested it but it don't work as expected and I really want to understand it. Whats the difference between both approaches?

Approach 1

def new
  @user = User.new
  respond_with(@user)
end

Approach 2

after_action :respond_with_call, only: [:new]  

def new
  @user = User.new
end

def respond_with_call
  respond_with(@user)
end

Upvotes: 1

Views: 69

Answers (1)

New Alexandria
New Alexandria

Reputation: 7324

respond_with does not work in and after_action, since the response has already been sent to the client.

Very similar to this question

Upvotes: 4

Related Questions