什么时候在Ruby(ActiveRecord)中需要范围解析

And*_*bbs 0 ruby activerecord ruby-on-rails

任何人都知道在这种情况下会发生什么?为什么需要使用self.class或范围解析::MyModel

class MyModel < ActiveRecord::Base

  belongs_to :other_model
  validate :custom_validation

  private
  def custom_validation
    if MyModel.where(some_field: 1).count > 0
      errors.add(:some_field, "foo")
    end
  end
end

# ... In some other part of the code base

my_model_instance = @other_model.my_models.find_or_initialize_by_some_field("foo")
my_model_instance.save
# Raises error - MyModel::MyModel is undefined
Run Code Online (Sandbox Code Playgroud)

上面的代码大部分时间都可以正常工作.但出于某种原因,在一种情况下它抛出了这个例外.更改custom_validation要使用的功能self.class而不是MyModel它的工作原理.

  def custom_validation
    if self.class.where(some_field: "bar").count > 0
      errors.add(:some_field, "error message")
    end
  end
Run Code Online (Sandbox Code Playgroud)

以前有人见过这样的事吗?为什么/如何将常数MyModel解释为MyModel::MyModel这种特定情况?

Ruby 2.0.0-p195Rails 3.2.13

编辑:澄清/添加有关为何需要范围解析的问题.

这个问题非常相似,但我仍然不清楚为什么MyModel没有范围分辨率的使用在大多数情况下都可以正常工作.

Jam*_*mes 5

您需要使用范围解析运算符,因此Ruby不会MyModelMyModel命名空间内查找.

def custom_validation
  if ::MyModel.where(some_field: 1).count > 0
    errors.add(:some_field, "foo")
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 等等是对的吗?我从未见过你不能在自己的身体中按名称引用一个类的情况.这并没有解决这个错误发生在什么情况的问题. (2认同)