Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mixin and call link_to from controller in Rails?

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?

like image 378
tribalvibes Avatar asked Oct 01 '10 22:10

tribalvibes


2 Answers

Compatible with Rails 3,4 and 5:

view_context.link_to
like image 117
Yacine Zalouani Avatar answered Sep 22 '22 14:09

Yacine Zalouani


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

For Rails 5, use the helpers proxy

helpers.link_to '...', '...'

For Rails 3 and 4, since you are using the helper from a controller you can use the view_context

# in the controller code
view_context.link_to '...', '...'

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

For Rails 2, 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

like image 26
house9 Avatar answered Sep 23 '22 14:09

house9