Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

naveen kumar asked in Rails

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

Reply

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

Reply

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

Reply

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
Reply

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

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.