Rails - How to include the mail_to helper inside of a controller

余生颓废 提交于 2020-01-13 06:10:12

问题


in my controller I need to format a json object, which is why I need to include several helpers.

So far I have the following in my controller:

  include ApplicationHelper
  include ActionView::Helpers::TextHelper
  include ActionView::Helpers::TagHelper

This works great for simple_format, problem is when the comment.content has a email address, rails trys to do a mailto link which breaks, showing the following error in the logs: "NoMethodError (undefined method `mail_to' for...."

Any ideas on how to add it in? I tried adding include ActionView::Helpers::UrlHelper but that did not work.

Thanks


回答1:


You can use view_context in your controller when doing 'view' tasks like generating links. The good thing about it is you don't have to include the view helpers in your controller.

e.g. in your controller you can create a variable which will be a html link with link_to.

link = view_context.link_to("link", your_awesome_path(@awesome))

I have not tested this but you should hopefully be able to do this in your controller:

email_link = view_context.mail_to(@user.email)

RyanB uses view_context in the paper_trail railscast: 255-undo-with-paper-trail

Not sure if this will solve your problem, because not sure what your doing with the JSON helpers etc. but it may help.




回答2:


I had solved this by the following

class CrazyPresenter
  include Rails.application.routes.url_helpers
  include ActionView::Helpers::TextHelper
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::UrlHelper

  def controller
    nil
  end

end


来源:https://stackoverflow.com/questions/5158513/rails-how-to-include-the-mail-to-helper-inside-of-a-controller

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