Skip to main content

How to add or call a particular action in all the controllers ?

Rails • Asked by naveen kumar

I want to store the user activity by using after_action in the all the controller for a specific action of those controller


Hi naveen,

I haven't actually tested this, but if I'm understanding your question, I believe you can get away with using your ApplicationController to do this since all your controllers should inherit from it.

class ApplicationController < ActionController::Base
  after_action :track_user, only: [:show, :edit] #whatever other actions you want to track

  def track_user
      # do something to track the user
  end
end

Here's a pretty good question on SO that shows 2 methods: http://stackoverflow.com/a/35589063/3670272


how to add a method in the private section of controller using your method?


If I undersand correct, just put the method below private

class ApplicationController < ActionController::Base
  after_action :track_user, only: [:show, :edit] #whatever other actions you want to track

  private

  def track_user
      # do something to track the user
  end
end

You're going to want to store the action details somehow in a method as Jacob mentioned called track_user or whatever naming convention you deem fit. You'll probably have to write the method that such it will track changes or actions and log the to some sort of table.

If you want to track model changes agnostic of the controller I'd suggest audited public_activity or the ever popular paper_trail all of these are pretty good for auditing purposes. But if you just want to track when a user triggers an action in the controller then a custom private method as Jacob spelled out is best, you'll just have to customize it for each action/use case and it could get big. So I'd suggest breaking it up to smaller methods if you have many actions to track


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.