Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access class variable in Model class

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>
like image 635
newBike Avatar asked Nov 29 '13 14:11

newBike


People also ask

How do you access one class variable from another class in Python?

How do you access a variable from another method in Python? Use the object attribute syntax to access a variable outside of a function. In a function named func , use the syntax func. variable = value to store value in variable as an attribute of func .

Can class methods access class variables?

Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.

How do you call a class variable in Ruby?

Defining a class variable A class variable looks like this: @@variable_name . Just like an instance or a local variable, you can set it equal to any type of data.

Can we access instance variable in class method Python?

Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls . Static methods don't have access to cls or self . They work like regular functions but belong to the class's namespace.


1 Answers

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
like image 185
apneadiving Avatar answered Oct 21 '22 04:10

apneadiving