Why isn't self always needed in ruby / rails / activerecord?

后端 未结 1 890
陌清茗
陌清茗 2020-12-01 02:01

In testing a getter/setter pair in a rails model, I\'ve found a good example of behavior I\'ve always thought was odd and inconsistent.

In this example I\'m dealing

相关标签:
1条回答
  • 2020-12-01 02:42

    This is because attributes/associations are actually methods(getters/setters) and not local variables. When you state "parent = value" Ruby assumes you want to assign the value to the local variable parent.

    Somewhere up the stack there's a setter method "def parent=" and to call that you must use "self.parent = " to tell ruby that you actually want to call a setter and not just set a local variable.

    When it comes to getters Ruby looks to see if there's a local variable first and if can't find it then it tries to find a method with the same name which is why your getter method works without "self".

    In other words it's not the fault of Rails, but it's how Ruby works inherently.

    Hope that helps.

    0 讨论(0)
提交回复
热议问题