Rails - override a setter for an active record attribute

1.2k views Asked by At

I am building a rails server in which some users follow changes in an other users location and get notified by websockets each time the location is updated.

Currently I call an update_location action instead of calling regular update in order to update the location and call the WebsocketRais trigger. This seems really odd to me and I think there should be a better way.

The only other option I know of is to call update action and check to see if the location is updated, and the notify the subscribers. This too seems very ugly to me.

I would like to be able to somehow override the Rails update of the resource, and notify the subscribers each time the location attribute is updated - something like a setter method for the location attribute that does other things than just set. Is it even possible? how would I be able to do it?

1

There are 1 answers

0
prcu On

I think it's ok to have separate method for this. However, if you want patch update_attributes you can write like this:

def update_attributes(attrs)
  update_location = attrs.delete(:update_location)
  super.tap { notify if update_location }
end

Or you can use custom attr & callback:

after_update :notify, if: :need_notify
attr_accessor :need_notify

# then
user.update_attributes location: smth, need_notify: true