How to mixin and call link_to from controller in Rails?

tribalvibes picture tribalvibes · Oct 2, 2010 · Viewed 20.8k times · Source

This seems like a noob question, but the simple answer is eluding me. I need to call link_to in an ActionController method to spit out an HTML link. ActionView::Helpers::UrlHelper.link_to calls url_for, but this calls the AV module's version instead of the controller's. I managed to coerce this into doing what I intended by putting

  #FIXME there must be a better way to mixin link_to
  alias_method :self_url_for, :url_for
  include ActionView::Helpers::UrlHelper
  alias_method :url_for, :self_url_for

in the controller. But, I'm still not sure why it works exactly. Could someone please explain the method scope and hiding that's happening here? What's a better way to mix in link_to (or generally, to include only some methods from a module) so I can call it in the controller (generating a flash string with a link is the use case.)

Please, no lectures about MVC--if anything, link_to should be in a module separate from url_for. Judging from the amount of noise on this, lots of people run into this seemingly trivial snag and end up wasting an hour doing it the "Rails way" when really what is wanted is a one minute hack to make my app work now. Is there a "Rails way" to do this with helpers perhaps? Or a better ruby way?

Answer

Yacine Zalouani picture Yacine Zalouani · Jun 19, 2012

Compatible with Rails 3,4 and 5:

view_context.link_to