【问题标题】:How to access class variable in Model class如何访问模型类中的类变量
【发布时间】:2013-12-15 18:04:23
【问题描述】:

我要定义类变量test,threshold

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

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

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

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>

【问题讨论】:

  • 为什么不用常量?

标签: ruby-on-rails rails-console


【解决方案1】:

我只会使用类方法:

class Order < ActiveRecord::Base
  def self.test
    123
  end

  def self.threshold
    { VIP: 500, PLATINUM: 20000 }
  end
end

常量也可以工作,但如果您已经拥有期望存在Order.testOrder.threshold 的代码,则必须更改代码以改为调用常量。另外,Avdi Grimm 给出了使用方法而不是常量 in a blog post 的一些充分理由。

访问类变量无法按您预期的方式工作的原因是 Ruby 限制对此类变量的访问。您需要直接定义访问器方法(如self.testself.threshold),或间接使用cattr_reader 之类的方法。如果您需要从外部写入变量,也可以使用cattr_accessor

不过,我通常建议避免使用类变量。他们有一些unintuitive behavior

【讨论】:

    【解决方案2】:

    这样做:

    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
    

    【讨论】:

    • Rails 4+ 使用类似的方法 mattr_accessor
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 2018-08-15
    • 2012-04-09
    • 1970-01-01
    相关资源
    最近更新 更多