How to access class variable in Model class

newBike picture newBike · Nov 29, 2013 · Viewed 8.8k times · Source

I want to define the class variable test, threshold

so that I can use Order.test, Order.threshold in my Rails app

but I can not access the class variable when using the rails console

I must misunderstand something, where's the problem? Thanks.

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

Here is the 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>

Answer

apneadiving picture apneadiving · Nov 29, 2013

Do this:

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

Order.test

Or I'd use constants:

class Order < ActiveRecord::Base
   TEST = 123
end

Order::TEST