如何从模型中调用辅助方法?

我在MongoID gem的Rails应用程序中使用MongoDB作为数据库。 我想用n aafter_create回调方法从模型中调用helper方法。 这怎么可能?
我的型号代码是:

class Department include ApplicationHelper after_create :create_news private def create_news @user = ApplicationHelper.get_current_users end end 

我的助手代码是:

 module ApplicationHelper def get_current_users current_user end end 

当我创建新部门时,会发生以下错误。

 undefined method `get_current_users' for ApplicationHelper:Module 

如何删除错误?
提前致谢。

我也使用mongoid并一直使用它。 虽然不应该是mongoid独有的。

 ApplicationController.helpers.my_helper_method 

如果你想要一个可以在视图中使用的辅助方法来返回当前用户,你可以在ApplicationController中这样做,例如:

 private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user 

然后你可以在任何视图中使用它。

如果你想在模型中使用一些任意方法来知道它正在处理什么用户, 当你在控制器中调用它时 @current_user 作为参数传递给方法

您的代码似乎不完整,所以我无法真正看到您要完成的任务,但这是一个非常标准的做法。

确保模块文件名称正确,在您的情况下就是application_helper.rb,它位于帮助程序库中。

您还可以尝试在ApplicationController中包含帮助程序(app / controller / application_controller.rb)。