views:

36

answers:

1

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?

+1  A: 

this doesn't really answer your question but there is an easier way

since you are using the helper from a controller you can actually access the @template member variable of the controller, the @template is the view and already has the UrlHelper mixed in

# in the controller code
@template.link_to '...', '...'

# instead of using your mixin code 
link_to '...', '...'

if you need to use the urlhelper from code other than the controller, your solution is probably the way to go

house9
ok thanks, that will work.
tribalvibes