2

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?

Carl Edwards
  • 13,826
  • 11
  • 57
  • 119

1 Answers1

0

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:

  • changed_attributes returns a Hash of model changes before save (meaning it is {} after a save because you have a clear, unchanged state for the current object). That won't work in your controller.
  • previous_changes returns a Hash of attributes that were changed by a save. This is what you want for your controller.

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
bschaeffer
  • 2,824
  • 1
  • 29
  • 59