2016-11-03 2 views
0

사용자 모델에 연결된 UserController의 POST 가입 양식이 있습니다. 사용자가 조직에 속해 있습니다. 가입 도중 새 조직 행을 만들고 적절한 관계를 생성중인 사용자에게 설정하려고합니다. 사용자의 생성 단계에서 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

I 그것이 더 적당하다고 생각하십시오 물줄기로 가능합니까 ... 물줄기가 할 수있는 것에 더 관심을 가졌기 때문에 묻고있는 것이기 때문입니다. 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 원자되지 않습니다 그래서이 생성, 아무것도 발견되지 않으면, 검색 (find)에 의해 구현되기 때문에 높은 동시성을 예상 할 때 사용하지 마십시오.

2) Model.create의 동작이 문서화되어 있는지 확실하지 않지만 채워진 속성이 .add() with a new record 인 경우 찾을 수 있습니다.

+0

훌륭한 답변을 제공 할뿐만 아니라 워터 라인이 요청에 키를 제공하여 관련 테이블에 레코드를 생성한다는 사실을 알게되었습니다. 귀하의 도움을 진심으로 감사드립니다. 추신 : 주제에 대한 의견을 반영하도록 질문을 업데이트합니다. – user1885523

관련 문제