2012-02-26 61 views
31

在Rails模型中查看方法时,有时会看到self.method_name,有时候只看到method_name。有什么区别和什么是指导知道什么时候使用self.以及什么时候不使用?Rails模型方法self。 vs plain

回答

24

1)当应用于方法定义时,'self'。将使其成为一种类方法,而plain将成为一种实例方法。

2)当应用于模型中的属性时,在更改属性时始终使用self很重要,否则不需要它。

因此,例如:

def some_method 
self.name = new_value # correct 
name = new_value # will not change the attribute 
end 
+1

甚至比楼上的回答更好。 – neversion 2016-10-10 01:41:30

+0

点2)让我疯狂。谢谢! – 2016-11-15 10:15:34