新手问题 自定义一个 Validate 里使用 self::count 为何提示没有方法呢?

jicheng1014 · October 06, 2014 · Last by jicheng1014 replied at October 06, 2014 · 1944 hits

今天在写一个验证的时候,不知道为何,使用 rspec 测是总是失败

提示消息是

Failures:

1) DefaultWarningConfig has a valid factory Failure/Error: expect(build(:default_warning_config)).to be_valid NoMethodError: undefined method count' for #<DefaultWarningConfig:0x007f9acdcaaf20> # ./app/models/default_warning_config.rb:7:inonly_one_record' # ./spec/models/default_warning_config_spec.rb:5:in `block (2 levels) in '

Finished in 0.99455 seconds (files took 2.29 seconds to load) 4 examples, 1 failure

可以看到,此处确实是 DefaultWarningConfig 这个对象

源码倒是蛮简单的

class DefaultWarningConfig < ActiveRecord::Base
  validates :pre_warning,:absolute_temp_min,:absolute_temp_max, :presence => true,:numericality => true
  validate :only_one_record

  def only_one_record
    p self.class
    errors.add(:id,"只允许有一条记录") if self::count !=0
  end
end

将此处的 self::count 换成 DefaultWarningConfig::count 即可

但是我觉得没道理啊 self.class 不就是 DefaultWarningConfig 么

方法里的 self 是 DefaultWarningConfig 的实例,不是 DefaultWarningConfig 本身。def 会打开一个新的作用域,def 里面的 self 跟外面的 self 不是一个东西。

self.class是DefaultWarningConfig说明 self 是 DefaultWarningConfig 的实例。

class DefaultWarningConfig

  COUNT = 10

  p self # DefaultWarningConfig 本身

  def instance_method
    p self # DefaultWarningConfig的一个实例
    P self.class # DefaultWarningConifg本身
    p self.class::COUNT # 10
    p DefaultWarningConfig::COUNT # 10
    p self::COUNT # Error
  end

end

#1 楼 @piecehealth 受教了,多谢

似乎跟C#和java 里有不同

You need to Sign in before reply, if you don't have an account, please Sign up first.