[英]module not loading in the controller (undefined_method error)
before applying the BeforeOrAfter
module in my view, trying to get it to work in the console. 在我的视图中应用BeforeOrAfter
模块之前,尝试让它在控制台中工作。 getting the NoMethodError: undefined method
before_or_after' for #` error: 得到NoMethodError: undefined method
before_or_after'为#`错误:
> s = Artist.find(1)
> s.events.each do |event|
> before_or_after(event.date)
> end
I chose to create a new modules subdirectory, app/modules/before_or_after.rb: 我选择创建一个新的modules子目录app / modules / before_or_after.rb:
module BeforeOrAfter
attr_reader :past
attr_reader :future
require "date"
def initialize
@datetime = DateTime.new
@future = []
@past = []
end
def before_or_after(datetime)
if datetime < DateTime.now
@past << datetime
else
@future << datetime
end
end
end
including it in application_controller.rb because all my controllers will be using it: 将它包含在application_controller.rb中,因为我的所有控制器都将使用它:
class ApplicationController < ActionController::Base
include BeforeOrAfter
I don't think that the rails environment is eager loaded before running the console. 在运行控制台之前,我不认为rails环境是急切加载的。 If you're in the console make sure you require that file before using that method. 如果您在控制台中,请确保在使用该方法之前需要该文件。
If you are running the full Rails app then your file should be auto loaded. 如果您正在运行完整的Rails应用程序,那么您的文件应该是自动加载的。 You can read more about auto loading and the need for requires here . 您可以在此处阅读有关自动加载和需求的更多信息。
To run in your rails app, please add below line in config/application.rb, 要在rails应用程序中运行,请在config / application.rb中添加以下行,
config.autoload_paths << Rails.root.join('app/modules')
To run in console, include your module first like, 要在控制台中运行,请首先包含您的模块,
include BeforeOrAfter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.