2

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.

carpeliam
  • 6,691
  • 2
  • 38
  • 42

1 Answers1

0

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.

iain
  • 16,204
  • 4
  • 37
  • 41
  • I'd be inclined to agree with you on the intended use for ActiveResource, if it weren't for this one bit of documentation for url_for: "If you instead of a hash pass a record (like an Active Record or Active Resource) as the options parameter, you’ll trigger the named route for that record. The lookup will happen on the name of the class. So passing a Workshop object will attempt to use the workshop_path route..." If they explicitly allow for an ActiveResource object, I think it'd behoove them to make it useful? – carpeliam Jan 09 '11 at 04:05
  • ActiveResource, just like ActiveRecord (and since Rails 3 every class extending ActiveModel::Naming) generate a link based on their name just like the documentation says: "The lookup will happen on the name of the class." You are always referring to your own representation of the object, rather than the original representation. With ActiveRecord, you are referring to your model, rather than the database that is behind it. Same goes for ActiveResource. Besides, it not even sure that the source of your ActiveResource class has an HTML representation, it might only be XML or JSON. – iain Jan 09 '11 at 12:03
  • Now that I think of it, there might be a way to get around it, and that is through `default_url_options`. This is a method you can define in your application_controller. I don't know if it'll work, but it might be worth looking into it. – iain Jan 09 '11 at 12:05