Use the model.urlRoot
property to specify the URL of the model if you wish to use the model 'outside' of a collection. It'll automatically append an id to the end of the URL if it's a new model (i.e. id==null
) and send a POST on creation. Else it'll fetch (GET) at the specified url.
If you don't want to have an id appended at the end: Just overwrite model.url
to generate the actual endpoint URL that you want to fetch/put/post to.
Collections also have a property called url
- if the url or urlRoot of the model isn't specified the collection's url is picked up as the root (if that model is part of that collection).
So you could just do either of these:
model.urlRoot = '/users/profile'; //appends id on put/delete requests
model.url = '/users/profile'; //direct endpoint. Can also be a function
collection.url = '/users/friends'; //fetch endpoint for collection. Could also be used by models to put to with appended id.
The Backbone's doc is quite comprehensive and self explanatory. I suggest you read these parts for example Model.urlRoot
UPDATE: As per your new URLs
I think the confusion is because of the way URLs are designed. It's not good practice to have end-points as plural/singular:
Ex:
/user/friends
- fine get all friends of user. But which user?
Better still: /users/{id}/friends
- get friends of a specific user.
GET specific friend for user: /users/{id}/friends/{id}
I suggest adding ids to your URLs to make the most of backbone's built in REST-able functionality. Else, just define your own properties and logic and have separate function like 'save' to fire $.ajax
calls yourself and do something on success/error callbacks.
Whether they are models or collections will totally be up to you. Fortunately/unfortunately there is more than one way to do it in Backbone. If you follow BB's way it'll offer a cleaner way of doing things since the framework expects and follows certain conventions. If not, you can always custom create. I've done both ways. Custom creating seems easier, following convention takes some planning but keeps it much cleaner albeit hides/abstracts away stuff from the programmer 'under the hood' whereas explicit ajax calls make it explicit.
It's a tradeoff. I suggest restructure your endpoints and use the url properties accordingly. Else just do what makes sense to you and your team and stick with it.