Julien Portalier
Julien Portalier

Reputation: 2999

Angular and Rails shallow resources

Rails offers a :shallow option to nested resources, which I rely on, because otherwise I'd have 4 or 5 nested resources, which would be very bad.

Shallow resources look like this:

resources :posts do
  resources :comments, :only => [:index, :create]
end
resources :comments, :only => [:show, :update, :destroy]

The problem I came upon to, is when trying to use Angular resources to map Rails resources, because ngResource only allows a single URI to be defined, so either /posts/:post_id/comments/:id or /comments/:id.

What I'd like is for ngResource to allow methods to override the URI and interpolations. For example:

app.factory('Comment', ['ngResource', function ($resource) {
    $resource('/comments/:id', { 'id': '@id', post_id: '@post_id' },
        index:   { method: 'GET',  url: '/posts/:post_id/comments', isArray: true },
        create:  { method: 'POST', url: '/posts/:post_id/comments' },
        show:    { method: 'GET' },
        update:  { method: 'PUT' },
        destroy: { method: 'DELETE' }
    );
}]);

Is this possible, maybe with another module than ngResource? Or should I just build two services: Comments and Comment?

Upvotes: 4

Views: 624

Answers (1)

Julien Portalier
Julien Portalier

Reputation: 2999

I actually looked at angular resource's source code from github, and found out that the current master allows actions to specify their own url parameter. The example I wrote in my question works perfectly possible with Angular 1.1.4+ (which isn't released yet).

Upgrading to the current angular master was the solution.

Upvotes: 2

Related Questions