I have several controllers (lets say one is the PostsController) that all inherit from the AuthenticatedController. Many methods in each of these child controllers perform similar CRUD actions and redirect back to the request referer,
I wanted to DRY up my controllers, so I refactored that code and put it all in a single method in the AuthenticatedController called do_action that will accept the object, action, and flash message.
class AuthenticatedController < ApplicationController
private
def do_action(action, obj, message, anchor='')
if obj.try(:action)
flash[:notice] = message
else
flash[:error] = 'Error Occurred'
end
redirect_to request.referer + anchor
end
end
class PostController < AuthenticatedController
def create
@post = Post.new
do_action(:save, @post, 'Created Successfully', "#post-#{@post.id}")
end
end
It works great, except that flash messages do not appear in my view anymore.
If I move do_action back into the PostsController, the flash messages appear as expected:
class PostController < AuthenticatedController
def create
@post = Post.new
do_action(:save, @post, 'Created Successfully', "#post-#{@post.id}")
end
private
def do_action(action, obj, message, anchor='')
if obj.try(:action)
flash[:notice] = message
else
flash[:error] = 'Error Occurred'
end
redirect_to request.referer + anchor
end
end
From what I understand after reading this SO question, flash is a method delegated to the request object. I'm able to access the request object in AuthenticatedController, I think request.referer?
Why can't I assign a message to flash from a method in AuthenticatedController?