这是一个对象orientated programming的问题;你不是从模型中调用变量,而是从类中访问属性或实例值(在范围等方面非常重要)。
-
你要么需要把这些变量作为class variable,并将它作为一个实例方法,还是有类方法返回它:
#app/models/model.rb
class Model < ActiveRecord::Base
cattr_accessor :sum #-> Model.sum class variable (static)
@@sum = 10
def self.sum
10 #-> Model.sum class method (static)
end
end
你怎么做,取决于什么您希望返回的数据类型。
- 如果数据是静态,使用类方法/可变
- 如果数据是动态,使用实例方法
以上是你要使用的代码,如果你想返回一个静态值。
如果你想返回动态值,你会使用:
#app/models/model.rb
class Model < ActiveRecord::Base
def score
self.games * self.goals # -> @model.sum instance method (dynamic)
end
end
-
不同的是,如果你使用一个类值,它是唯一可用通过类的初始化。 IE你可以拨打Model.sum
并有权访问该记录。
实例方法/值仅通过实例的类的访问:
@model = Model.find 5 #-> creates a new instance of the class
@model.sum #-> pulls the dynamic sum value of the class instance
修复
在你的情况,你最好使用实例方法:
#app/models/abc.rb
class Abc < ActiveRecord::Base
def score
10
end
end
#app/controllers/first_controller.rb
class FirstController < ApplicationController
def get_score
@abc = Abc.new
@abc.sum #-> 10
end
end
这样,你的数据将是动态的,允许你操纵它等等。
你可以使用'abc'类的任何对象来获得'score'。 –