geddy / model

Datastore-agnostic ORM in JavaScript
265 stars 55 forks source link

How do I update defaults before validation? #199

Closed OscarGodson closed 10 years ago

OscarGodson commented 10 years ago

I was told to check out the before/after events. I setup this:

  this.beforeValidate = function () {
    this.created_on = Date.now();
    if (!this.enabled) this.enabled = false;
    if (!this.archived) this.archived = false;
    console.log(this)
  };

based off the docs which show

  this.beforeValidate = function () {
    // `this` will refer to the model instance
    this.name = this.name.toLowerCase();
  };

The problem with this is this doesn't help and it thinks these are not set still (the is present check fails as these are required). In this case, the console.log(this) returns this:

{ type: 'Experiment',
  _saved: false,
  isValid: [Function],
  save: [Function],
  updateProperties: [Function],
  updateAttributes: [Function],
  toJSON: [Function],
  toData: [Function],
  toObj: [Function],
  toString: [Function],
  _getAssociation: [Function],
  _createAssociation: [Function],
  _removeAssociation: [Function],
  _commitAssociationChanges: [Function],
  clone: [Function],
  created_on: 1401262137933,
  enabled: false,
  archived: false }

Note on the bottom the properties added. However, this isn't where the other properties are stored and therefore this doesn't work to set defaults. Any ideas?

OscarGodson commented 10 years ago

updated title to be more accurate

mde commented 10 years ago

Fixed in 9d655a966309fa7a2105abc2a2e750a600c9d3e2 by passing the params used in the create method to beforeValidate. Pushed to NPM in v0.5.14.

OscarGodson commented 10 years ago

mde commented 10 years ago

Kinda disappointed this didn't animate.

OscarGodson commented 10 years ago

Its supposed to! Try refreshing!?

mde commented 10 years ago

WTH. Ah, must be a low-fi placeholder while it's processing on the backend. MUCH BETTER