Skip to content

Overriding model getters/setters? #66

Closed

Description

@dxg

Hey, say I have a model like:

User = db.define('user',{
    email: String
  },{
  validations: {
    email: orm.validators.unique()
  },
  hooks: {
    beforeSave: function() {
      this.email = email.toLowerCase();
    }
  }
});

All is jolly, however:

user1 = db.models.user.new({email: 'a@b.c'});
user1.save(...);
...
user2 = db.models.user.new({email: 'A@b.c'});
user2.save(...);

We now have two duplicate users.
(I actually have a unique index on the table to prevent this, but it throws an ugly error when saving)

I can think of two ways of solving this:

  1. Add a beforeValidate hook.
  2. Make it possible to add custom setters/getters for model properties.

I imagine it working something like this:

User = db.define('user',{
    email: String
  },{
  setters: {
    email: function(val) {
        return val.toLowerCase();
    }
  }
});

Or maybe even more fancy:

User = db.define('user',{
    email: String
  },{
  methods: {
    email: {
        set: function(val) {
            this.setAttribute('email', val.toLowerCase());
        }
    }
  }
});

where it defaults to the standard getter as one isn't specified, and setAttribute calls the default setter.

What do you think?

Activity

  1. dresende commented on Mar 5, 2013

    @dresende
    Owner

    It's strange the uniqe validator is not working, since it just searches the model for that property. You can have your own unique validator, maybe you can spot the bug :p

    Maybe the beforeSave should be before validations to allow people to make changes. The idea of custom getters/setters is not bad but maybe not now, I'm still cleaning bugs from last version. Let us stabilise as much as possible before that.

  2. dresende commented on Mar 5, 2013

    @dresende
    Owner

    Try now:

    User = db.define('user',{
        email: String
      },{
      validations: {
        email: orm.validators.unique()
      },
      hooks: {
        beforeSave: function() {
          this.email = this.email.toLowerCase();
        }
      }
    });
  3. dxg commented on Mar 5, 2013

    @dxg
    CollaboratorAuthor

    Thanks, that fixes it.
    Ok.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions