couchrest / couchrest_extended_document

Extends CouchRest with helpers and such
Apache License 2.0
24 stars 5 forks source link

STI Equivalent #6

Open tapajos opened 14 years ago

tapajos commented 14 years ago

Issue from: http://github.com/couchrest/couchrest/issues#issue/18

Hello,

Has anyone already thought of starting to work on something similar to active record's single table inheritance ?

Let's guess two classes :

class User < CouchRest::ExtendedDocument
end

class Admin < User
end

Currently, couchrest wouldn't see that the admin is in fact a user. We couldn't retrieve all users (admins included).

The idea would be, when a class inherits from an other, to add an attribute "couchrest-sti", which would have the subclass value. When we do a User.all, it's retrieve all the objects having "couchrest-type" defined to user. But if it has a "couchrest-sti" defined, it'd instantiate the object as the class defined in that attribute. Not as a user.

I really need this. So I'd be willing to work on it. But is it something you'd find useful and that'd have a chance to get implemented to the trunk ?

samlown commented 14 years ago

Defining an 'sti' column is not such a good idea as it would only help with one level of inheritance. For anyone wanting to implement this, I'd suggest defining your own view which accepts the multiple types you're searching for, for example:

class User < CouchRest::ExtendedDocument
  view_by :all_types,
    :map => "
      function(doc) {
        switch (doc['couchrest-type']) {
          case 'User':
          case 'Admin':
            emit(doc['_id'], 1);
          default:
        }
      }
    "
end