Search code examples
ruby-on-railsactiveresource

Is there a nice way to use url_for with ActiveResource?


I'm using ActiveResource in my rails app to talk to another rails app (both are version 2.3.5). I'd like to link to the page for a particular resource object, but there doesn't seem to be any nice way to do that. The ugly way I've figured out is to add a line to my routes.rb file that mimics my resource, like this:

# environment.rb, or in the config/environments/*.rb files
PERSON_URL = "people.example.com"

# person.rb
class Person < ActiveResource::Base
  self.site = "http://#{PERSON_URL}"
end

# routes.rb
map.resources :people # or persons, or whatever

# my_view.html.erb
<%= link_to person.name, person_url(person, :host => PERSON_URL) %>

But this is pretty ugly. Now I've got an extra route floating around in my app that doesn't actually exist. There has to be a better way. Does the model itself have any clues for getting the url for itself? Anybody have any tips? Thanks.


Solution

  • ActiveResource wasn't meant to be used this way. It is implemented to be very close to ActiveRecord. Routes are per definition local. If you are referencing another site, you are not linking to this application anymore, thus the normal routes won't help you (much).

    The default helpers work on naming conventions alone. The only thing url helpers will do with objects is call to_param to get the identifier for individual resources.

    I don't know if there is a gem that can help you, but I fear you have to make your own helpers.