codecraig
codecraig

Reputation: 3158

Generate URL in controller (rails)

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?

Upvotes: 1

Views: 16889

Answers (2)

gparis
gparis

Reputation: 1267

Check the method ActionController::Base#url_for

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

Upvotes: 5

Peter Brown
Peter Brown

Reputation: 51697

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

Upvotes: 3

Related Questions