Updating DB Fields in RailwayJS upon Create and Update

138 Views Asked by At

I'm new to RailwayJS (but not Rails) and I had a question about the best way to save my created_at field on Create, and updated_at field on Update.

This is my model (db/schema.js):

var Post = define('Post', function() {
    property('title', String);
    property('content', Text);
    property('desc', String);
    property('created_at', Date);
    property('updated_at', Date);
});

So in my posts_controller.js, I'm setting the "created_at" field before the create method:

action(function create() {
    req.body.Post.created_at = new Date;
    Post.create(req.body.Post, function (err, post) {
      // Handle error or do stuff
    });
});

...and I'm pretty much doing the same for the update method:

action(function update() {
    body.Post.updated_at = new Date;
    this.post.updateAttributes(body.Post, function (err) {
      // Handle error or do stuff
    }.bind(this));
});

Couldn't (shouldn't) this be done in a before filter in my model? If so, how?

2

There are 2 best solutions below

0
On BEST ANSWER

As you have mentioned in the last comment it can be done in railwayJS like this:

before(setDate, {only: ['create', 'update']});

action(function update() {
  console.log(body.Post.updated_at);

  this.post.updateAttributes(body.Post, function (err) {
      if (!err) {
          flash('info', 'Post updated');
          redirect(path_to.post(this.post));
      } else {
          flash('error', 'Post can not be updated');
          this.title = 'Edit post details';
          render('edit');
      }   
  }.bind(this));
});


function setDate(){
    body.Post.updated_at = new Date();
    next();
}
0
On

For now, I kept what I had posted in my question...

But if I wanted to do this in a before filter it would go something like this:

before(setDate, {only: ['create', 'update']});

...

function setNewDate() {
  // Update the request model with the date
  ...
  next();
}