question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Nested Associations

See original GitHub issue

Hi,

I was wondering if there was any way to “restangularize” nested associations without having to perform two API calls? i.e. Say I had a /ships endpoint and everywhere I use a ship I always need to know about it’s crew. My API actually returns the crew information as part of the response. e.g. /ships/1 returns:

    {
        id:1, 
        name: "Queen Anne's Revenge", 
        crew: [{
            id:1, 
            name: "Blackbeard"
        }]
    }

What I’d like to be able to do is somehow let restangular know that my response contains a crew collection and that it should also be restangularized to give me all the restangular method decoration goodness on the crew members.

This would also be useful on 'has one" associations too. ie. (for want of a better example) If requesting by crew member first: /crew/1 returning:

    {
        id:1, 
        name: "Blackbeard", 
        ship: {
            id:1, 
            name: "Queen Anne's Revenge"
        }
    }

It’d be good if we were able to tell it to restangularize Blackbeard’s ship.

Great library BTW - Thanks,

Dan

Issue Analytics

  • State:closed
  • Created 10 years ago
  • Comments:11 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
fstbrazcommented, Jun 29, 2016

Hi @mgonto , same problem like @airlst . My restangular object is on a service, and the configuration on a config file for all the app. Where would I place the call to restangularizeElement?

BTW, what I get from my api is a thing like this:


{
  "total": 2,
  "per_page": 10,
  "current_page": 1,
  "last_page": 1,
  "next_page_url": null,
  "prev_page_url": null,
  "from": 1,
  "to": 2,
  "data": [
    {
      "id": 1,
      "start_date": "2006-08-20 05:11:32",
      "end_date": "2009-10-18 23:03:06",
      "created_at": "2016-06-23 08:41:51",
      "updated_at": "2016-06-23 08:41:51",
      "unity": {
        "id": 224,
        "code": 20060810,
      },
      "user": [
        {
          "id": 1,
          "username": "Kiara Runolfsdottir",
          "created_at": "2016-06-23 15:56:56",
          "updated_at": "2016-06-23 15:56:56"
        },
        {
          "id": 2,
          "username": "Zoe Dach",
          "created_at": "2016-06-23 15:56:56",
          "updated_at": "2016-06-23 15:56:56"
        },
        {
          "id": 3,
          "username": "Mrs. Zelma Johnston III",
          "created_at": "2016-06-23 15:56:56",
          "updated_at": "2016-06-23 15:56:56"
        },
      ]
    }
  ]
}

and my servicel is this:


'use strict';

angular.module('ng-laravel').service('ScaleService', function($rootScope, Restangular,CacheFactory) {
    /*
     * Build collection /scale
     */
    var _scaleService =  Restangular.all('scale');

    if (!CacheFactory.get('scalesCache')) {
        var scalesCache = CacheFactory('scalesCache');
    }

    /*
     * Get list of users from cache.
     * if cache is empty, data fetched and cache create else retrieve from cache
     */
    this.cachedList = function() {
        // GET /api/scale
        if (!scalesCache.get('list')) {
            return this.list();
        } else{
            return scalesCache.get('list');
        }

    };


    /*
     * Get list of users
     */
    this.list = function() {
        // GET /api/scale
        var data = _scaleService.getList();

        scalesCache.put('list',data);
        return data;
    };



    /*
     * Pagination change
     */
    this.pageChange = function(pageNumber,per_page) {
        // GET /api/scale?page=2
        return _scaleService.getList({page:pageNumber,per_page:per_page});
    };


    this.cachedShow = function(id) {
        // GET /api/scale/:id
        if (!scalesCache.get('show'+id)) {
            return this.show(id);
        } else{
            return scalesCache.get('show'+id);
        }
    };

    /*
     * Show specific scale by Id
     */
    this.show = function(id) {
        // GET /api/scale/:id
        var data = _scaleService.get(id);
        scalesCache.put('show'+id,data);
        return data;
    };


    /*
     * Create scale (POST)
     */
    this.create = function(scale) {
        // POST /api/scale/:id
        _scaleService.post(scale).then(function() {
            $rootScope.$broadcast('scale.create');
        },function(response) {
            $rootScope.$broadcast('scale.validationError',response.data.error);
        });
    };

    /*
     * Update scale (PUT)
     */
    this.update = function(scale) {
        // PUT /api/scale/:id
        scale.put().then(function() {
            $rootScope.$broadcast('scale.update');
        },function(response) {
            $rootScope.$broadcast('scale.validationError',response.data.error);
        });
    };


    /*
     * Delete scale
     * To delete multi record you should must use 'Restangular.several'
     */
    this.delete = function(selection) {
        // DELETE /api/scale/:id
        Restangular.several('scale',selection).remove().then(function() {
            $rootScope.$broadcast('scale.delete');
        },function(response){
            $rootScope.$broadcast('scale.not.delete');
        });
    };

    /*
     * Search in scale
     */
    this.search = function(query,per_page) {
        //console.log(query);
        // GET /api/permission/search?query=test&per_page=10
        if(query != ''){
            return _scaleService.customGETLIST("search",{query:query, per_page:per_page});
        }else{
            return _scaleService.getList();
        }
    }



});

Tnks !

1reaction
mrdanparkercommented, Jun 6, 2013

Yeah, initially I was thinking what you said about exposing the “restangularize” method so that it can be called from the onElementRestangularized hook. Would be great if you could do that?

As for an API, how about if there was a withAssociations method that takes a properties map with a form something along the lines of:

{
    many: ['crewMembers', 'prisoners'],
    one: ['captain', 'preciousCargo']
}

Then once the response is returned it (the library) knows it needs to restangularize a collection of crewMembers, a collection of prisoners, a single captain, and a single preciousCargo. The strings would be both the property on the JSON, plus will double up as the route (chained with the parent route). Or maybe each of the items in the many and one arrays should be maps themselves so that their routes/other stuff can be configured. I may be overcomplicating now!

So ultimately, you’d be able to do:

Restangular.one('ships', 1).withAssociations({many:['crewMembers'], one:['captain']})

Thoughts?

Anyway, in the meantime just exposing “restangularize” would be great.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Preloading Nested Associations with Ecto - Thoughtbot
A look at how to preload database associations using Elixir's Ecto library.
Read more >
ActiveRecord nested associations - ruby on rails
I want to get the whole data using all nested associations as a hash that I could reformat (or map) and sent to...
Read more >
How to Access Deeply Nested Associations in Ruby on Rails ...
Trying to access associations that are two levels deep (also known as deeply nested associations) in Rails is discouraged, yet not impossible.
Read more >
How To...Rails: Complex Associations, Nested Forms, and ...
In this post, I'll build on that example to develop more complex model associations, and build a single nested form that allows users...
Read more >
Nested association mapping - Wikipedia
Nested association mapping (NAM) is a technique designed by the labs of Edward Buckler, James Holland, and Michael McMullen for identifying and dissecting ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found