2015-12-29 103 views
2

我刚刚开始学习Ruby on Rails,我想知道是否有一种方法可以访问模型方法中定义的变量。我有一个控制器,我想访问变量。 我有一个模型访问控制器中模型方法内定义的变量。

class abc 
def score 
    sum = 10 
end 
end 

而且还有一个控制器

class FirstController < ApplicationController 
def get_score 
end 
end 

所以我想变总和的方法get_score值。我怎样才能做到这一点?

+0

你可以使用'abc'类的任何对象来获得'score'。 –

回答

2

这是一个对象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 

这样,你的数据将是动态的,允许你操纵它等等。

2

在ruby方法返回最后一个语句值,如果return语句没有明确返回。 您可以通过以下方式访问比分:

class FirstController < ApplicationController 
def get_score 
     Abc.new.score 
end 
end 

记住类名总是使用大写字母。

1

在你abc.rb模型文件:

class Abc < ActiveRecord::Base 
    def self.score 
    sum = 10 
    end 
end 

现在你可以使用型号名称访问得分方法在任何地方想。

class FirstController < ApplicationController 
def get_score 
    Abc.score # you will get 10 here 
end 
end 
相关问题