为什么不能自我总是需要在红宝石/导轨/ ActiveRecord的?导轨、红宝石、自我、ActiveRecord

2023-09-08 15:49:08 作者:似人间绝色

在测试的getter / setter对在轨的模型,我发现的行为我一直以为是奇数和不一致的一个很好的例子。

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.

在这个例子中,我对付类文件夹<的ActiveRecord :: Base的

In this example I'm dealing with class Folder < ActiveRecord::Base.

文件夹belongs_to的:父母,:将class_name =&GT; 文件夹

在getter方法​​,如果我使用:

On the getter method, if I use:

def parent_name
  parent.name
end

...或...

...or...

def parent_name
  self.parent.name
end

......结果是完全一样的,我得到的父文件夹的名称。不过,如果我使用的getter方法​​...

...the result is exactly the same, I get the name of the parent folder. However, in the getter method if I use...

def parent_name=(name)
  parent = self.class.find_by_name(name)
end

...父变成零,但是如果我用...

... parent becomes nil, but if I use...

def parent_name=(name)
  self.parent = self.class.find_by_name(name)
end

...然后再它的工作原理。

...then then it works.

所以,我的问题是,为什么你有时需要申报self.method,为什么你能只使用一个局部变量?

So, my question is, why do you need to declare self.method sometimes and why can you just use a local variable?

这似乎需要/在ActiveRecord的使用的不一致,我想更好地了解这个,所以我不觉得我总是猜测我是否需要申报自己或没有。什么时候你应该/你不应该在ActiveRecord模型使用的自我?

It seems the need for / use of self in ActiveRecord is inconsistent, and I'd like to understand this better so I don't feel like I'm always guessing whether I need to declare self or not. When should you / should you not use self in ActiveRecord models?

推荐答案

这是因为属性/协会实际上是方法(getter / setter方法​​),而不是局部变量。当你说出父母=价值红宝石假设你想赋给局部变量的父母。

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.

某处堆栈有一个setter方法​​高清父=,并呼吁,您必须使用self.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.

当谈到干将红宝石查看是否有一个局部变量第一,如果不能找到它,然后它试图找到这就是为什么你的getter方法​​作品,未经自我同名的方法。

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

在换句话说,它不是Rails的故障,但它的红宝石是如何工作的本质。

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

希望有所帮助。