views:

138

answers:

1

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.

+1  A: 

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!

François Beausoleil