gpt4 book ai didi

ruby-on-rails - 在模型中访问时使用 attribute_name 或 self.attribute_name 是更好的做法

转载 作者:太空宇宙 更新时间:2023-11-03 17:47:39 26 4
gpt4 key购买 nike

对于包含列 :first_name 和 :last_name 的用户模型,编写 full_name 方法的最佳方式是什么。两者似乎都有效。

class User < ActiveRecord::Base

def full_name
first_name + last_name
end

end

或者

class User < ActiveRecord::Base

def full_name
self.first_name + self.last_name
end

end

我看过下面的 SO 帖子,但不确定

为什么在 ruby​​/rails/activerecord 中并不总是需要 self?

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."

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

为什么要使用“self”来访问 ActiveRecord/Rails 模型属性?

"Often the use of self is to force Ruby to recognize that as a method call and not mis-interpret it as a variable. Without prior knowledge of a method called day=, then day = "x" looks to Ruby like a variable assignment. self.day = "x" is always a method call.

The reason this is trouble is because the name and name= methods are added dynamically after the User class file has been parsed. The first thing Rails does when using a model is make methods for the associated database fields, but this happens after your user.rb file is parsed."

Why use "self" to access ActiveRecord/Rails model properties?

最佳答案

阵营 1:约定优于配置。此外,self.first_name 不适用于私有(private)访问器。

阵营 2:你一眼就知道什么是什么,而如果没有明确的接收者,你可能会忘记你有什么方法。

最后,这是一个意见问题,所以我投票结束。不过,深思:

bbatsov style guide :

Avoid self where not required. (It is only required when calling a self write accessor.)

GitHub style guide (基于 bbatsov 风格指南):

Avoid explicit use of self as the recipient of internal class or instance messages unless to specify a method shadowed by a variable.

关于ruby-on-rails - 在模型中访问时使用 attribute_name 或 self.attribute_name 是更好的做法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com