1

I have an action in my controller that renders JSON back to the client:

@data = [{label:"foo", url:"..."}, ...]

render :json => @data

Basically "data" is an array of objects that each have a label and url property. The want to generate the URL on the server-side instead of handing this data to the client and having it iterate over it to generate the URL strings.

If I could use the "link_to" method it would look like this:

link_to "foo", {:action => 'some_action', :foobar => {}}

Basically link to the /foobar/some_action

What's the best way to generate the URL while in the controller since I don't have the handy "link_to" method?

2 Answers 2

5

Check the method ActionController::Base#url_for

For Rails 3 see ActionDispatch::Routing::UrlFor#url_for

2
  • I chose this as the answer b/c it will also let me specify the protocol (http, https) which I need. However, I didn't test whether the link_to would pick the correct protocol based on the HTTP request that came in. Thanks for both answers.
    – codecraig
    Commented Mar 3, 2011 at 10:43
  • Thanks. Note that I suggested url_for because I think you only need a URL, not the link tag that returns link_to. In fact, link_to uses url_for to generate the URL.
    – gparis
    Commented Mar 4, 2011 at 11:28
3

You can include the view helper methods in your controller just like any other module, and those methods will be available:

class MyController < ApplicationController
  include ActionView::Helpers::UrlHelper

  def ajax_method
    link_to "foo", {:action => 'some_action', :foobar => {}}
  end
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.