Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resource mapping in a Ruby on Rails URL (RESTful API)

I'm having a bit of difficulty coming up with the right answer to this, so I will solicit my problem here. I'm working on a RESTFul API. Naturally, I have multiple resources, some of which consist of parent to child relationships, some of which are stand alone resources. Where I'm having a bit of difficulty is figuring out how to make things easier for the folks who will be building clients against my API.

The situation is this. Hypothetically I have a 'Street' resource. Each street has multiple homes. So Street :has_many to Homes and Homes :belongs_to Street. If a user wants to request an HTTP GET on a specific home resource, the following should work:

http://mymap/streets/5/homes/10

That allows a user to get information for a home with the id 10. Straight forward. My question is, am I breaking the rules of the book by giving the user access to:

http://mymap/homes/10

Technically that home resource exists on its own without the street. It makes sense that it exists as its own entity without an encapsulating street, even though business logic says otherwise.

What's the best way to handle this?

EDIT! In spirit of becoming a good StackOverflow citizen, I've come back with a supported code block for how to implement they above.

map.resources :streets,
              :has_many => :homes
              :shallow => true

This will create both types of routes that I was looking for.

like image 379
randombits Avatar asked Apr 10 '10 23:04

randombits


1 Answers

If your Home records can only belong to one Street, then the relationship won't be confused when you're examining a Home individually. You'll still be able to back-track to the associated Street record for whatever reason.

It's in situations where you have a many-to-many relationship that de-nesting your REST structure can get you into trouble. If a particular record only makes sense in a particular context, and you remove that context, obviously there is confusion.

I think in your particular case you may not need to implement both approaches, but instead go with the "flatter" approach that reduces the complexity of the URL.

like image 200
tadman Avatar answered Oct 21 '22 01:10

tadman