code tunes

Web applications, software engineering, Ruby on Rails, Cake PHP, JavaScript, etc.

NamedScopeBehavior upgrade

I have just added a small functionality to my NamedScopeBehavior.

Now you can use named scopes from multiple models at once in a single find query. Assuming that given models are associated through belongsTo or hasOne association.

Quick example:

// model definitions
class User extends AppModel {
  var $actsAs = array(
    'NamedScope' => array(
      'activated' => array('User.activated' => 1)
    )
  );
  var $belongsTo = array(
    'Group'
  );
}
 
class Group extends AppModel {
  var $actsAs = array(
    'NamedScope' => array(
      'admins' => array('Group.name' => 'admins')
    )
  );
}
 
// in controller
$this->User->find('all', array('scope' => array('User.activated', 'Group.admins')));

New version can be found in repository.

Related posts

2 comments

Written by Michał Szajbe

September 15th, 2008 at 12:39 am

2 Responses to 'NamedScopeBehavior upgrade'

Subscribe to comments with RSS

  1. Could you use that behavior as an emulator for polymorphism?…

    Lucian Lature

    15 Sep 08 at 10:26

  2. Well, I didn’t look at it that way, but I think it could work to some extent :)

    Assuming that Comment belongsTo many commentable models (Article being one of them), you could do:

    class Comment extends AppModel {
      var $actsAs = array(
        'NamedScope' => array(
          'promotedArticles' => array(
            'Comment.model' => 'Article',
            'Article.promoted' => 1
          )
        )
      );
    }

    Such scope would find all comments to promoted articles.

    Scope’s conditions are copied to find query without any modifications so it is OK to have multi-model conditions in Comment’s model named scope.

    Of course you still need some support for polymorphism before. I believie that PolymorphicBehavior or something similar would be fine.

    Michał Szajbe

    16 Sep 08 at 21:26

Sorry, comments are closed for this post.