2016-11-03 42 views
0

我有一個註冊表單,通過POST來連接到User模型的UserController。用戶屬於組織。我希望在註冊過程中創建一個新的組織行,併爲正在創建的用戶設置適當的關係。 Sails/Waterline在用戶的創建步驟中可以實現嗎?創建期間的Sails.js /水線關聯

signup.ejs

<h1>Signup</h1> 
<form method="POST" action="/organization/users/"> 
    <input type="email" name="email"> 
    <input type="password" name="password"> 
    <input type="text" name="organizationName"> 
    <input type="submit" value="submit"> 
</form> 

user.js的(模型)

module.exports = { 
    attributes: { 
     email: { 
      type: 'email', 
      required: true, 
      unique: true 
     }, 
     password: { 
      type: 'string', 
      minLength: 6, 
      required: true 
     }, 
     organization: { 
      model: 'organization' 
     } 
    } 
}; 

UserController.js

module.exports = { 
    create: function (req, res) { 
    var options = { 
     name: req.param('email'), 
     password: req.param('password') 
    }; 

    User.create(options).exec(function(err, user) { 
     return res.redirect("/users"); 
    }); 

    } 
}; 

回答

1

我認爲這是更合適的這是可能的水線...因爲你問的是更關心什麼水線可以做。檢查出waterline documentation

如果名稱不存在,則可以創建組織的新記錄並將該ID分配給user.organization。

創建行動

create: function (req, res) { 
    var options = { 
     name: req.param('email'), 
     password: req.param('password') 
    }; 

    Organization.findOrCreate({name: req.param('organization')}) 
     .exec(function(err,org){ 
     options.organization = org.id; 
     User.create(options).exec(function(err, user) { 
      return res.redirect("/users"); 
     }); 
     }); 
    } 

但是,如果你想創建一個新的記錄每次創建一個新用戶的時候,你可以這樣做:

創建行動

create: function (req, res) { 
    var options = { 
     name: req.param('email'), 
     password: req.param('password'), 
     organization: { 
     name: req.param("organization") 
     } 
    }; 

    User.create(options).exec(function(err, user) { 
     return res.redirect("/users"); 
    }); 
    } 

水線每次創建一個新組織用戶被創建。

注:

1)findOrCreate不是原子那麼預計高併發的時候,因爲它是通過查找和執行,如果沒有找到,一個創建不使用它。

2)我不知道如果Model.create的行爲被記錄在案,但可以使用。新增一個填充屬性的()with a new record時找到它。

+0

您不僅提供了一個很好的答案,而且還了解到Waterline將通過在請求中提供密鑰來在關聯表中創建記錄。你的幫助是真正的讚賞。 PS,我會更新這個問題以反映你對這個主題的評論。 – user1885523