How to call helper method from model?

廉价感情. 提交于 2020-01-01 16:48:09

问题


I use MongoDB as database in my Rails application with MongoID gem. I want to call helper method from model with n aafter_create callback method. How is it possible?
My model code is:

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

And my helper code is:

module ApplicationHelper
  def get_current_users
    current_user
  end
end

When I create new department then following error occur.

undefined method `get_current_users' for ApplicationHelper:Module

How to remove error?
Thanks in advance.


回答1:


I also use mongoid and use this all the time. Shouldn't be unique to mongoid though.

ApplicationController.helpers.my_helper_method



回答2:


If you want a helper method that you can use in your views to return the current user, you can do so in your ApplicationController, something like this for example:

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

Then you can use this in any view.

If you want some arbitrary method in a model to know what user it's dealing with, pass @current_user in as an argument to the method when you call it in your controller.

Your code seems incomplete so I can't really see what you're trying to accomplish, but this is a pretty standard practice.




回答3:


Make sure the module file is named properly, meaning in your case application_helper.rb and it's located on the helpers library.

You can also try to include the helper in the ApplicationController (app/controller/application_controller.rb).



来源:https://stackoverflow.com/questions/14088945/how-to-call-helper-method-from-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!