简体   繁体   English

Ruby模块包含问题

[英]Ruby Module Include Question

I have a CommonFunctions Module inside the lib/ folder. 我在lib /文件夹中有一个CommonFunctions模块。 I have a Question Model, which includes the CommonFunctions module. 我有一个问题模型,其中包括CommonFunctions模块。 Now I am trying to access the favorite function of the CommonFunctions like Question.favorite. 现在,我尝试访问CommonFunctions的收藏夹功能,例如Question.favorite。 But I am getting NoMethodError. 但是我收到了NoMethodError。 I have included the code. 我已经包含了代码。 Can anyone please tell me where I am doing the mistake 谁能告诉我我在哪里做错了

Error 错误

NoMethodError: undefined method `favorite' for Class:0x00000100e11508

Inside lib/CommonFunctions.rb 内部lib / CommonFunctions.rb

module CommonFunctions
  def favorite(object_id)
  end
end

Inside app/models/Question.rb 内部应用程序/模型/Question.rb

require 'lib/CommonFunctions.rb'
class Question
  extend CommonFunctions
end

I am executing the following code from the script/console 我正在从脚本/控制台执行以下代码

   Question.favorite(1)

Thanks 谢谢


This was a duplicate of How do I properly include a module and call module functions from my Rails model? 这与我如何从Rails模型中正确包含模块和调用模块函数重复

Your code is correct. 您的代码是正确的。 Make sure you have the current version of the classes loaded in the console (try reload! ). 确保已在控制台中加载了当前版本的类(尝试reload! )。

As a sidenote: if you rename CommonFunctions.rb to common_functions.rb, it will be autoloaded by rails and you don't need the require. 附带说明:如果将CommonFunctions.rb重命名为common_functions.rb,它将由rails自动加载,并且不需要require。

The module method is an instance method when you want it to be a class method. 当您希望模块方法是类方法时,它是一个实例方法。 Use the code below instead 使用下面的代码代替

module CommonFunctions   
  def self.favorite(object_id)   
  end 
end

Using the word "self" defines the method as a class method (or static) 使用单词“ self”将方法定义为类方法(或静态方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM