1

Is it possible to define a temp field / virtual field in geddy model?

Like in the form I've use the input fields tmpFirstName and tmpLastName but when submitted I want to store the information in a single column name.

Thanks

ginad
  • 1,863
  • 2
  • 27
  • 42

1 Answers1

1

This can be trivially achieved with the new lifecycle methods (thanks to you!).

In your controller:

  this.create = function (req, resp, params) {
    var self = this
      , person = geddy.model.Person.create(params);

    person.firstname = params.firstname;
    person.lastname = params.lastname;

    if (!person.isValid()) {
      this.respondWith(person);
    }
    else {
      person.save(function(err, data) {
        if (err) {
          throw err;
        }
        self.respondWith(person, {status: err});
      });
    }
  };

In your model:

  this.defineProperties({
    name: {type: 'string'}
  });

  this.beforeSave = function () {
    this.name = this.firstname + ' ' + this.lastname;
  }

Note that you don't declare the "virtual" properties, otherwise geddy will store them in the database.

Ben
  • 1,292
  • 9
  • 17
  • Thanks Ben, so right now we can't declare it inside the model like what rails is doing with `attr_accessor` so we just call `.create(params)` instead of defining it one by one after calling `.create()`? – ginad Nov 01 '13 at 07:09
  • I tried that code earlier and couldn't figure out why the (virtual) attributes weren't being set with `.create`. You're right that this is weird. I looked at our geddy-passport code, and `confirmPassword` seems to be working fine there as a virtual attribute. I will file an issue and look into what's going on. – Ben Nov 01 '13 at 07:25
  • Yes that's what I'm wondering also because geddy has a validatesConfirmed so I'm wondering how to use this if `.create` doesn't read virtual attributes. Thanks again Ben – ginad Nov 01 '13 at 11:35