Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update serialized attribute without callbacks in Rails

I am trying to update a serialized attribute with some data in an after_save callback on the same object.

I don't want any callbacks to be triggered, for various reasons (side-effects, infinite loop). The typical way to achieve this would be to use update_column, but unfortunately that doesn't work with serialized attributes.

I am aware that I could put conditionals on my callbacks to avoid them getting called again, but it feels that there should be a form of update_attribute which doesn't trigger callbacks, but still works with serialized attributes.

Any suggestions?

like image 797
Martin May Avatar asked Nov 03 '22 14:11

Martin May


2 Answers

This is what I do

serialize :properties, Hash

def update_property(name, value)
  self.properties[name] = value
  update_column(:properties, properties)
end
like image 127
axsuul Avatar answered Nov 15 '22 04:11

axsuul


Sharing an example below how you can update serialize attribute without callbacks.

Suppose you have a train object, and there is a serialize attribute in that table called: "running_weekdays", that store on which day that particular train runs.

train = Train.last
train.running_weekdays
=>  {"Mon"=>"true", "Tues"=>"true", "Wedn"=>"true", "Thur"=>"true", "Frid"=>"true", "Sat"=>"true", "Sun"=>"true"}

Now suppose you want to set the value for all weekdays as false except 'Monday'

changed_weekdays = {"Mon"=>"true", "Tues"=>"false", "Wedn"=>"false", "Thur"=>"false", "Frid"=>"false", "Sat"=>"false", "Sun"=>"false"}

Now you can update this by using update_column as below:

train.update_column(:running_weekdays,  train.class.serialized_attributes['running_weekdays'].dump(changed_weekdays))

Hope this will help.

like image 45
Sumit Pahuja Avatar answered Nov 15 '22 05:11

Sumit Pahuja