本章緊接著前一篇, 我們要來實作Delete的功能
這篇參考此Youtube:Building a Sails Application: Ep9 - Deleting a user account.
我們到UserController.js
去新增我們的delete程式碼
UserController.js 新增 destroy function 1
2
3
4
5
6
7
8
9
10
11
12
13
14
destroy : function ( req , res , next ){
console . log ( "Hi, destroy" );
User . findOne ( req . param ( 'id' ), function foundUser ( err , user ){
if ( err ) return next ( err );
if ( ! user ) return next ( 'User doesn\'t exist.' );
User . destroy ( req . param ( 'id' ), function userDestroyed ( err ) {
if ( err ) return next ( err );
});
res . redirect ( '/user' );
});
},
我們注意到if(!user) return next('User doesn\'t exist.');
我們也把這一段敘述加到edit action
裡面
UserController.js 修改 edit action 1
2
3
4
5
6
7
8
9
10
11
12
13
edit : function ( req , res , next ){
console . log ( "hi, edit!" );
//Find the user from the id passed in via params
User . findOne ( req . param ( 'id' ), function foundUser ( err , user ){
if ( err ) return next ( err );
if ( ! user ) return next ( 'User doesn\'t exist.' );
res . view ({
user : user
});
});
},
然後我們回到views\user\index.ejs
, 加入以下程式碼
views\user\index.ejs 加入destroy (使用POST方法) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<div class= "container" >
<h3> Users</h3>
<table class= "table" >
<tr>
<th> ID</th>
<th> Name</th>
<th> Title</th>
<th> Email</th>
<th></th>
<th></th>
<th></th>
</tr>
< % _.each(users, function(user){ %>
<tr data-id= "<%= user.id %>" data-model= "user" >
<td> < %= user.id %></td>
<td> < %= user.name %></td>
<td> < %= user.title%></td>
<td> < %= user.email%></td>
<td><a href= "/user/show/<%= user.id %>" class= "btn btn-sm btn-primary" > Show</a></td>
<td><a href= "/user/edit/<%= user.id %>" class= "btn btn-sm btn-warning" > Edit</a></td>
<td>
<form action= "/user/destroy/<%= user.id%>" method= "POST" >
<input type= "hidden" name= "_method" value= "delete" />
<input type= "submit" class= "btn btn-sm btn-danger" value= "Delete" />
<input type= "hidden" name= "_csrf" value= "<%= _csrf %>" />
</form>
</td>
</tr>
< %}) %>
</table>
</div>
注意到我們對destroy
使用POST
方法, 其他的action
我們是用GET
方法
由於我們的destroy是用另外一個form, 所以我們要在新增一個hidden的_csrf, 否則我們會沒有辦法access網頁
好, 完成之後, 存檔, 重啟sails
瀏覽器輸入http://localhost:1337/user
就可以玩玩看delete的功能了!