【问题标题】:Access method in controller from model模型中控制器中的访问方法
【发布时间】:2013-02-02 02:24:41
【问题描述】:

刚开始使用 Rails,正在研究如何访问我的模型中的方法。

在控制器中,我尝试以下操作: @testString = Work.testMethod

class Work < ActiveRecord::Base<br>
  def testMethod
    return "string from test method"
  end
end

这会导致“WorksController#index 中的 NoMethodError”(未定义的方法)。 我将不胜感激。

而且.. 为什么在搭建“work”时,rails 会在控制器名称后附加一个“s”?模型名称为 Work,控制器为:works_controller

【问题讨论】:

    标签: ruby-on-rails ruby methods model


    【解决方案1】:

    使用self:

    class Work < ActiveRecord::Base
       MY_MESSAGE = "ALL THE BEST"
    
       def self.testMethod
         return "string from test method"
       end
    end
    

    self 用于调用类级别的方法。现在你可以像下面这样在任何地方调用它:

    Work.testMethod #=> "string from test method"
    Work::MY_MESSAGE #=> "ALL THE BEST"
    

    如果您使用instance_level 方法,您需要创建class 的实例,然后您可以在对象上调用方法。但是模型实例是在您想要创建新记录时创建的,所以当您不想创建记录时,我更喜欢使用 self 方法。

    如果你有记录,你可以调用:

     class Work < ActiveRecord::Base
       def testMethod
         return "string from test method"
       end
    end
    
    work_record = Work.find(your_condition)
    work_record.testMethod
    

    【讨论】:

    • 谢谢,这很有效,很简单。这如何与模型中声明的变量一起工作?我的意思是从控制器访问它们。
    • 你的意思是constant变量??
    • 基于上面的例子,我可以访问我的模型中的方法,谢谢!关于变量,我的意思是模型本地的 var。可通过模型中的方法访问。
    【解决方案2】:

    您所说的概念是引入class 方法。需要借助 self 关键字在 Work 类本身上定义该方法。

    可以这样做:

    class Work < ActiveRecord::Base
       def self.testMethod
         return "string from test method"
       end
    end
    

    要回答您的第二个问题,Rails 是一个固执己见的框架,它强制采用复数您的 Controller 和 Table 名称的模式。这确实是为了在语法上更正确。

    如果您想调整复数形式,可以使用Inflections

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      相关资源
      最近更新 更多