【问题标题】:Updating DB Fields in RailwayJS upon Create and Update在创建和更新时更新 RailwayJS 中的数据库字段
【发布时间】:2012-08-08 17:54:12
【问题描述】:

我是 Rails 的新手(但不是 Rails),我对在 Create 上保存 created_at 字段和在 Update 上保存 updated_at 字段的最佳方法有疑问。 p>

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

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

【问题讨论】:

    标签: node.js railway.js


    【解决方案1】:

    正如您在上一条评论中提到的,它可以像这样在 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();
    }
    

    【讨论】:

      【解决方案2】:

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

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

      before(setDate, {only: ['create', 'update']});
      
      ...
      
      function setNewDate() {
        // Update the request model with the date
        ...
        next();
      }
      

      【讨论】:

        猜你喜欢
        • 2012-09-07
        • 1970-01-01
        • 2012-12-24
        • 2020-07-14
        • 1970-01-01
        • 2019-01-26
        • 1970-01-01
        • 2011-03-24
        • 1970-01-01
        相关资源
        最近更新 更多