[英]Access method in controller from model
剛開始使用Rails,弄清楚如何訪問模型中的方法。
在控制器中,我嘗試以下操作: @testString = Work.testMethod
class Work < ActiveRecord::Base<br>
def testMethod
return "string from test method"
end
end
這將導致“ WorksController#index中出現NoMethodError”(未定義的方法)。 我將不勝感激。
And ..為什么在腳手架“工作”時,rails會在控制器名稱后附加一個“ s”? 型號名稱為Work,控制器為:works_controller
使用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
您正在談論的概念正在引入一個class
方法。 需要借助self
關鍵字在Work
類本身上定義該方法。
可以按照以下步驟完成:
class Work < ActiveRecord::Base
def self.testMethod
return "string from test method"
end
end
為了回答您的第二個問題,Rails是一個自以為是的框架,它強制采用了將Controller和Table名稱復數的模式。 這確實是為了在語法上更正確。
如果您想調整多元性,可以使用Inflections來進行 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.