【问题标题】:Why can't I directly access instance variables in Active Record callback?为什么我不能在 Active Record 回调中直接访问实例变量?
【发布时间】:2016-02-14 08:27:47
【问题描述】:

在 Active Record 回调中,我总是看到 examples 使用 self.variable。有时,不需要self. 前缀,所以他们只使用variable(参见related question)。

根据我的阅读,这两种引用类实例变量的方法是使用访问器函数,而@variable 将直接访问该变量。在我的代码中,我尝试使用@variable,但它不起作用 - 好像还没有定义@variable...你不能在 Active Record 回调中直接访问实例变量吗?

另外,我还没有为这个特定变量定义访问器函数,所以当我说self.variable 或variable 时实际会发生什么(我已经尝试了这两种方法,并且两者都在赋值的 LHS 之外工作) ?

This question 本质上是我要问的,但我不明白答案并想要更多说明(我无法评论答案,因为我是 Stack Overflow 的新手)。他的回答是这样的:

[密码] 与 self.password 相同。 ActiveRecord 定义方法,而不是实例变量来访问与数据库相关的内容。这就是为什么您无法使用@password 访问它的原因。

但是我见过的回调方法总是定义在模型的类中,这应该让它们可以访问实例变量,对吧?他还这么说:

PS:回调只是对您的对象的方法调用。唯一的区别是 Rails 为你调用它们,而不是你自己。

那么他是否可能意味着回调方法不是从对对象的引用中调用的?例如。而不是称为model_instance.callback_method,它只是称为callback_method?如果 callback_method 是类实例方法,如何在不引用类实例的情况下找到它?即使它确实以这种方式工作,它怎么知道self.variable 是什么?

【问题讨论】:

  • 你是如何定义回调的?

标签: ruby-on-rails activerecord callback instance-variables


【解决方案1】:

不能在 Active Record 回调中直接访问实例变量吗?

您可以从任何实例方法访问实例变量,包括那些用作 ActiveRecord 回调的变量。

另外,我还没有为这个特定的变量定义一个访问器函数,所以当我说 self.variable 或 variable 时实际会发生什么(我已经尝试了这两种方法,并且两者都在赋值的 LHS 之外工作)?

首先,重要的是要了解这两种语法之间的区别。 variable = 123 会将值 123 分配给局部变量。 self.variable = 123 将在 self 上调用名为 variable= 的方法并将 123 作为参数传递。

> class Foo
>   def x=(value)
>     puts "Foo#x called with #{ value }"
>   end
>
>   def bar
>     x = 123       # local variable assignment, `x` only exists inside the `bar` method.
>     self.x = 456  # calls `x=` 
>   end
> end

> Foo.new.bar
Foo#x called with 456

可能有点令人困惑的是,使用隐式接收器调用的方法与引用局部变量共享相同的语法。

> class Bar
>   def x
>     "In method x"
>   end
>
>   def foo
>     # No local variable `x` has been initialized yet, so references to `x` will call the method with that name.
>     puts x           # calls method `x` and prints "In method x".
>                      # This example is equivalent to `puts self.x`.
>
>     x = "Hello"      # Now that a local variable is defined it will hide the method `x`.
>     puts x           # references the local variable and prints "Hello".
>     puts self.x      # calls the method `x` and prints "In method x".
>   end
> end

> Bar.new.foo
In method x
Hello
In method x

其次,您需要知道 ActiveRecord 为模型表的每一列创建访问器方法。假设我有一个模型User(id: integer, name: string, age: integer)。 ActiveRecord 将定义实例方法id、name 和age 来读取属性和id=、name= 和age= 来设置属性。

实例变量完全是另外一回事。您无法使用@id、@name、@age 等实例变量访问数据库属性。

那么他是否可能意味着回调方法不是从对对象的引用中调用的?

不,ActiveRecord 回调确实会调用对象上的实例方法。

【讨论】:

  • 这很有帮助,谢谢!我也刚找到this article,基本上和你说的一样。他们说您可以通过self[:variable] = value 访问实际变量,并且这包含了 write_attribute 和 read_attribute - 这是否意味着您总是必须通过 Rails 定义的访问器?你什么时候会使用self[:variable] 而不是self.variable?
  • 我发现大多数开发人员使用self.variable 而不是self[:variable]。但是,这些方法是等效的,并且可以互换,除非在文章中提到的那些围绕覆盖属性方法的情况下。一般来说,我建议避免在模型中定义与数据库列同名的方法(这通常会导致混淆)。很高兴知道self[:variable]、read_attribute 和write_attribute 可用,以防万一您需要它们。
  • 如果您使用的属性名称是动态生成的,self[:variable] 也可以用作方便。例如attr_name = first_name? ? :first_name : :last_nameself[attr_name] # Returns either first_name or last_name
  • self[:variable] 可以在覆盖 getter 方法的情况下使用,这样您就可以获得价值并且不会出现无限循环错误。
【解决方案2】:

我相信您不太了解 Rails 属性不存储在实例变量中。您的所有属性(由数据库表模式定义)都存储在一个实例变量 @attributes 中,该变量永远不会被直接访问,因为它是 Rails 实现细节的一部分。

例子:

class Thing < ActiveRecord::Base
  # assume that we have a 'name' column in the database

  def foo
    # correct ways to access the name
    name
    self.name
    self[:name]

    # this contains name value and other name metadata
    # but you shouldn't use it
    @attributes[:name]

    # this holds nil as that variable has no relation to the "name" attribute
    @name
  end
end

在回调中,它的工作方式与在所有其他方法中相同——您可以访问自己定义的实例变量,但不能将数据库属性作为实例变量访问。

 class Thing < ActiveRecord::Base
  attr_accessor :secret

  after_initialize do
    @secret = '123'
  end

  before_create do
    p @secret
  end

  after_validation :on_validation
  def on_validation
    p @secret
  end
end

如果您尝试创建Thing 对象,基于块的before_create 回调和基于方法的after_validation 回调都可以访问after_initialize 回调中定义的实例变量@secret。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    相关资源
    最近更新 更多