Skip to content
This repository has been archived by the owner on Jul 14, 2021. It is now read-only.

active-record associations ? #7

Open
cgHome opened this issue Oct 4, 2013 · 2 comments
Open

active-record associations ? #7

cgHome opened this issue Oct 4, 2013 · 2 comments

Comments

@cgHome
Copy link

cgHome commented Oct 4, 2013

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

Chris

@bfanger
Copy link
Owner

bfanger commented Oct 4, 2013

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.

@shlensky
Copy link

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?

xob pushed a commit to cognibox/angular-activerecord that referenced this issue Apr 16, 2019
CBX-35 - Fix notEmpty validation
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants