Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Overriding model getters/setters? #66

Closed
dxg opened this issue Mar 5, 2013 · 3 comments
Closed

Overriding model getters/setters? #66

dxg opened this issue Mar 5, 2013 · 3 comments

Comments

@dxg
Copy link
Collaborator

dxg commented Mar 5, 2013

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?

@dresende
Copy link
Owner

dresende commented Mar 5, 2013

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.

@dresende
Copy link
Owner

dresende commented Mar 5, 2013

Try now:

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

@dxg
Copy link
Collaborator Author

dxg commented Mar 5, 2013

Thanks, that fixes it.
Ok.

@dxg dxg closed this as completed Mar 5, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants