1

I'm new with geddy and I'm getting confuse on how to use the model events.

My model has a slug field and I want to generate the slug (base on the name they entered) before I save any records.

In other words how do I do this in geddy?

rails model:

before_save :generateSlug
private:
 def generateSlug
   self.slug = self.name.parameterize
 end

sample model code: model/page.js

slugify = require('slug');
var Page = function(){
  this.defineProperties({
   slug: {type: 'string'},
   name: {type: 'string', required: true}
  });

  this.beforeSave = function(){
   this.slug = slugify(this.name);
  }
}
exports.Page = Page;

When I run p = geddy.model.Page.create({name: 'hello world'}); and p.save(function(e,d){ console.log(d); }) slug is undefined

ginad
  • 1,863
  • 2
  • 27
  • 42

1 Answers1

1

You can use the beforeValidate lifecycle method to do this.

Try this:

this.beforeValidate = function () {
  this.slug = slugify(this.name);
};

Note: This did not work prior to Model@0.3.2, which had a bugfix for inconsistent lifecycle methods.

Ben
  • 1,292
  • 9
  • 17
  • Thanks but I can't see any afterCreate in the documentation and when I tried this.beforeSave my slug still gets an undefined instead of the slug string. – ginad Oct 24 '13 at 08:41
  • Hm, can you post some sample code so I can see what you're doing? – Ben Oct 24 '13 at 20:40
  • 1
    Hello Ben, I've just updated the question to add the sample code. Thanks – ginad Oct 28 '13 at 03:25
  • Hi ginad, I've updated the answer. `beforeSave` is an event, so you have to listen for it. However, I will file an issue in Model because `afterCreate`is called when it is a property, but many of the other events are not. This is inconsistent, and probably our fault. Sorry! – Ben Oct 28 '13 at 06:00
  • Thanks Ben but when I defined this.on('beforeValidate') or any event inside the model I get `TypeError: Object [object Object] has no method 'on'` – ginad Oct 28 '13 at 09:04
  • This looks like a real bug. I'll change it so that the other event functions get called too. You can track the progress here: https://github.com/mde/model/issues/109 Sorry for the trouble! – Ben Oct 28 '13 at 19:56
  • Hi Ginad, this bug has been fixed in https://github.com/mde/model/pull/111. I am not sure when it will be pushed to NPM as there have been quite a number of possibly breaking updates to Model since the last release. – Ben Oct 29 '13 at 01:03
  • Hello Ben, is it possible to use mde/model in my geddy application? Thanks – ginad Oct 29 '13 at 03:16
  • Yes, model is what geddy already uses. There is nothing special you have to do to use it. – Ben Oct 29 '13 at 03:35
  • I mean using the latest model in github? Thanks – ginad Oct 29 '13 at 04:11
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/40154/discussion-between-ben-and-ginad) – Ben Oct 29 '13 at 06:29