How to invoke method once per page reload? defining before_filter in ApplicationController is failed because of multiple controllers used to perform action
Asked
Active
Viewed 202 times
1 Answers
2
When you say multiple controllers are used in one action, could you be more specific? Normally a before_filter in the controller responsible for the action would suffice.
If you want your before filter to affect specific methods in multiple controllers then place the method itself in the ApplicationController but the before_filter in each of the controllers that contain the action.
class ApplicationController
def foo
@bar = 'bar'
end
end
class UserController
before_filter :foo, :only => [:method1]
def method1
...
end
def method2
...
end
end
class StuffController
before_filter :foo, :only => [:method2]
def method1
...
end
def method2
...
end
end
class UnimportantController
# No before filter, neither of these methods will call :foo
def method1
...
end
def method2
...
end
end

Matt
- 13,948
- 6
- 44
- 68
-
i.e. I have a PageController and CommentController... PageController load normaly and CommentController loads by AJAX and render comments below each page. That's why both of them run before_filter from ApplicationController and invoke before_filter. Am I wrong? – Marcin Petrów May 21 '13 at 08:25
-
Use your before_filters as suggested above to limit them to only the important actions in PageController, more of a scalpel vs sledgehammer approach. Added a third controller example with no filters. – Matt May 21 '13 at 08:34
-
if you want to avoid to run the before_filter, just for xhr calls (and not a specific action as described in the answer) you can do as described here http://stackoverflow.com/questions/5114529/is-there-a-way-in-rails-to-skip-a-before-filter-if-the-request-is-xhr – VP. May 21 '13 at 08:41