Rails - 如何在控制器中包含 mail_to 助手
在我的控制器中,我需要格式化一个 json 对象,这就是为什么我需要包含几个助手.
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
这对 simple_format 很有用,问题是当 comment.content 有一个电子邮件地址时,rails 尝试做一个中断的 mailto 链接,在日志中显示以下错误:NoMethodError (undefined method `mail_to' for...."
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...."
关于如何添加它的任何想法?我尝试添加 include ActionView::Helpers::UrlHelper 但这没有用.
Any ideas on how to add it in? I tried adding include ActionView::Helpers::UrlHelper but that did not work.
谢谢
在执行查看"任务(例如生成链接)时,您可以在控制器中使用 view_context.这样做的好处是您不必在控制器中包含视图助手.
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.
例如在您的控制器中,您可以创建一个变量,该变量将是一个带有 link_to 的 html 链接.
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 在 paper_trail railscast 中使用 view_context:255-undo-with-paper-trail
RyanB uses view_context in the paper_trail railscast: 255-undo-with-paper-trail
不确定这是否能解决您的问题,因为不确定您对 JSON 助手等做了什么,但它可能会有所帮助.
Not sure if this will solve your problem, because not sure what your doing with the JSON helpers etc. but it may help.