我刚刚开始学习 Ruby on Rails,我想知道是否有一种方法可以访问模型方法中定义的变量。我有一个 Controller ,我想在其中访问变量。 我有一个模型
class abc
def score
sum = 10
end
end
还有一个 Controller
class FirstController < ApplicationController
def get_score
end
end
所以我想在方法get_score中获取变量sum的值。我怎样才能实现这个目标?
最佳答案
这是一个对象 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
您的操作取决于您希望返回的数据类型。
- If the data is static, use a class method / variable
- If the data is dynamic, use an instance method
如果您想返回静态值,上面是您将使用的代码。
如果您想返回动态值,您可以使用:
#app/models/model.rb
class Model < ActiveRecord::Base
def score
self.games * self.goals # -> @model.sum instance method (dynamic)
end
end
--
区别在于,如果您使用class值,则只能通过类的初始化来使用它。在 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
这样,您的数据将是动态的,允许您对其进行操作等。
关于ruby-on-rails - 访问 Controller 中模型方法内定义的变量。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34505131/