简体   繁体   中英

Ruby Module Include Question

I have a CommonFunctions Module inside the lib/ folder. I have a Question Model, which includes the CommonFunctions module. Now I am trying to access the favorite function of the CommonFunctions like Question.favorite. But I am getting 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

module CommonFunctions
  def favorite(object_id)
  end
end

Inside app/models/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?

Your code is correct. Make sure you have the current version of the classes loaded in the console (try 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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