Ruby-on-rails Rails 模型方法自。与普通

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9449487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:54:49  来源:igfitidea点击:

Rails Model method self. vs plain

ruby-on-rails

提问by bachposer

When looking at methods in Rails models, sometimes I see self.method_nameand sometimes just a method_name. What's the difference and what is the guide to know when to use self.and when not to?

在查看 Rails 模型中的方法时,有时我会看到self.method_name,有时只是一个method_name. 有什么区别,知道何时使用self.和何时不使用的指南是什么?

回答by Veraticus

self.method_name indicates a class method; method_name indicates an instance method.

self.method_name 表示类方法;method_name 表示实例方法。

You can read a lot more about class and instance methods at this blog postor, if you'd prefer something a bit more official, the Programming Ruby class section.

您可以在这篇博文中阅读更多关于类和实例方法的信息,或者,如果您更喜欢更正式的内容,请阅读Ruby 编程类部分

回答by Forrest

1) When applied to method definitions, 'self.' will make it a class method, while plain will be an instance method.

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

2) When applied to attributes in a model, it's important to always use the self when changing an attribute, but you won't need it otherwise.

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

so for example:

所以例如:

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