在创建和更新中更新铁路中的数据库字段

时间:2012-08-08 17:54:13

标签: node.js railway.js

我是RailwayJS的新手(但不是Rails),我对最佳方式有疑问,可以将我的created_at字段保存在创建和updated_at字段上更新

这是我的模型(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);
});

所以在我的posts_controller.js中,我在create方法之前设置了“created_at”字段:

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

...我对update方法做了同样的事情:

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

这不能(不应该)在我的模型中的过滤器中完成吗?如果是这样,怎么样?

2 个答案:

答案 0 :(得分:3)

正如你在上一篇评论中提到的那样,可以在铁路这样做:

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();
}

答案 1 :(得分:0)

现在,我保留了我在问题中发布的内容......

但是,如果我想要before过滤器中执行此操作,它将会是这样的:

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

...

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