ruby-on-railscontrollerpublic-activity

Public Activity - Creating activities based on certain attribute changes


I'm using the Rails gem, Public Activity and wanted to create an activity instance for every update action but with a catch. I only want the event created if a certain attribute is changed. In my case it would be a post's time_zone. Here is how activities are currently created in my posts controller:

class PostsController < ApplicationController
  def update
    ...
    @post.create_activity :update, owner: current_user
    ...
  end
end

I couldn't find anything in the docs that explain how to do the aforementioned. Is there a way to setup, let's say a conditional that checks if the time_zone has changed to make this happen?


Solution

  • ActiveModel::Dirty handles tracking changes to attributes in your model. There are a number of ways to tell whether or not a specific attribute did change:

    So, you need the following in your controller

    def update
      @post = Post.find(params[:id])
      @post.update!(post_params)
    
      if @post.previous_changes.key?('time_zone')
        @post.create_activity(:update, owner: current_user)
      end
    end