0

我是RailwayJS(但不是Rails)的新手,我有一个关于在Create 上保存我的字段和在Update上保存字段的最佳方法的问题。created_atupdated_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的方法之前,我设置了“created_at”字段create

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

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

4

2 回答 2

3

正如您在上一条评论中提到的那样,它可以在 railJS 中完成,如下所示:

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();
}
于 2012-11-06T08:22:38.920 回答
0

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

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

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

...

function setNewDate() {
  // Update the request model with the date
  ...
  next();
}
于 2012-10-12T14:23:04.997 回答