Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing ActiveRecord attribute value in before_save hook

I needed to fix the encoding of an ActiveRecord attribute and decided to do it in a before_save hook. And at this point I noticed an unexpected feature. When I wanted to change the value of the attribute, simple using the attribute_name=XY did not work as I expected. Instead of that I needed to use self[:attribute_name]=XY. So far did not recognise this behaviour and I used AR.attribute_name=XY. What is the reason for this? Does this behaviour relate to the hook or something else? Thanks for explanation.

like image 957
fifigyuri Avatar asked Feb 28 '23 09:02

fifigyuri


1 Answers

This is in fact a Ruby "feature":

def value=(x)
  p x
end

def run
  value = 123
end

run
# => 123

In #run above, doing value assigns a local variable, not anything else. If you want to call #value=, you have to specify the receiver:

def run
  self.value = 123
end

run
123
# => nil

Hope this helps!

like image 57
François Beausoleil Avatar answered Mar 01 '23 23:03

François Beausoleil