Changing the value of the ActiveRecord attribute in the before_save element

I needed to fix the encoding of the ActiveRecord attribute and decided to do it in hook_ before. And at that moment I noticed an unexpected feature. When I wanted to change the attribute value, the simple use of attribute_name=XY did not work as I expected. Instead, I needed to use self[:attribute_name]=XY . So far, this behavior has not been recognized, and I used AR.attribute_name=XY . What is the reason for this? Is it connected with a hook or something else? Thanks for the explanation.

+4
source share
1 answer

This is actually a Ruby function:

 def value=(x) px end def run value = 123 end run # => 123 

In #run above, value assigns a local variable, not something else. If you want to call # value =, you must specify the recipient:

 def run self.value = 123 end run 123 # => nil 

Hope this helps!

+8
source

Source: https://habr.com/ru/post/1303877/


All Articles