angular-activerecord icon indicating copy to clipboard operation
angular-activerecord copied to clipboard

active-record associations ?

Open cgHome opened this issue 11 years ago • 2 comments

hi, any plans for support of active-record associations? thanks!

Chris

cgHome avatar Oct 04 '13 05:10 cgHome

It isn't "planned", but it is certainly on my wishlist. Do you know other implementations of relational mapping in JavaScript?

I currently busy with other projects. If a pull request adds HAL support (http://stateless.co/hal_specification.html) I'll gladly merge it in.

bfanger avatar Oct 04 '13 18:10 bfanger

I would like to suggest the following interface for associations:

In your models.

 module('myApp', ['ActiveRecord']);
 module('myApp').factory('Task', function (ActiveRecord, Comment) {

    return ActiveRecord.extend({        
        $urlRoot: '/api/tasks',

        $constructor: function Task(properties) {
            this.$initialize.apply(this, arguments);
        },

        // An example method for loading associated records
        $loadComments: function () {
            // $hasMany will load all associated records by calling Comment.fetchAll({params: {task_id: this.id}})
            // and return's array, with few methods:
            // * $push - add new record to array
            // * $build - build new record, and add it to array
            this.$comments = this.$hasMany(Comment, {foreign_key : 'task_id'}); 
        }
    });
 });

 module('myApp').factory('Comment', function (ActiveRecord) {

    return ActiveRecord.extend({        
        $urlRoot: '/api/comment',

        $constructor: function Comment(properties) {
            this.$initialize.apply(this, arguments)
        }
    });
 }); 

In your controllers.

module('myApp').controller('TaskCtrl', function ($scope, Task, $document) {

    Task.fetchOne(7).then(function (task7) {
        $scope.task = task7;
        $scope.task.$loadComments();
    });

    $scope.addComment = function(properties) {
        // $push method will automatically add 'task_id' to new comment
        $scope.task.$comments.$push(new Comment(properties));
    };

    $scope.removeComment = function(comment) {
        // $destroy will automatically remove comment from $scope.task.$comments
        comment.$destroy();
    };

    $scope.save = function() {
        // $saveAll method will save task and all associated comments
        $scope.task.$saveAll();
    }
});

Do you like this DSL?

shlensky avatar Oct 19 '14 08:10 shlensky