如何访问模型类中的类变量

新自行车

我想定义类变量testthreshold

这样我就可以Order.test, Order.threshold在Rails应用程序中使用

但是在使用Rails控制台时我无法访问class变量

我一定误会了,问题出在哪里?谢谢。

class Order < ActiveRecord::Base
  @@test=123
  @@threshold = {
    VIP: 500,
    PLATINUM: 20000
  }

这里是 rails console

irb(main):001:0> Order.class_variables
=> [:@@test, :@@threshold]
irb(main):002:0> Order.test
NoMethodError: private method `test' called for #<Class:0x007fe5a63ac738>
呼吸暂停

做这个:

class Order < ActiveRecord::Base
   cattr_reader :test, :threshold
   self.test = 123
   self.threshold = {
     VIP: 500,
     PLATINUM: 20000
   }
end  

Order.test

或者我会使用常量:

class Order < ActiveRecord::Base
   TEST = 123
end

Order::TEST

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章