railway.js中嵌套的资源:说不能POST
我正在尝试一个名为railway.js的MVC框架(它位于Node,Express,Mongoose和Mongo之上)。
我试图让嵌套的资源工作。 我做了以下的脚手架命令:
railway g scaffold user name email description railway g scaffold setup title description
然后我改变了routes.js文件到:
exports.routes = function (map) { map.resources('users',function(user) { user.resources('setups'); }); });
做railway r
给我所希望的:
user_setups GET /users/:user_id/setups.:format? setups#index user_setups POST /users/:user_id/setups.:format? setups#create new_user_setup GET /users/:user_id/setups/new.:format? setups#new edit_user_setup GET /users/:user_id/setups/:id/edit.:format? setups#edit user_setup DELETE /users/:user_id/setups/:id.:format? setups#destroy user_setup PUT /users/:user_id/setups/:id.:format? setups#update user_setup GET /users/:user_id/setups/:id.:format? setups#show users GET /users.:format? users#index users POST /users.:format? users#create new_user GET /users/new.:format? users#new edit_user GET /users/:id/edit.:format? users#edit user DELETE /users/:id.:format? users#destroy user PUT /users/:id.:format? users#update user GET /users/:id.:format? users#show
当我启动服务器,添加一个用户(恰好是4e4b61e39f0d60d834000002),然后去http:// localhost:3000 / users / 4e4b61e39f0d60d834000002 /设置/新 ,它说我“不能POST”。
我错过了什么? 什么是好的debugging方法?
我也尝试在UserSchema对象中添加一个元素: setups: [SetupSchema]
。 (我们不应该这样做吗?)
提前致谢。
在你的setup_controller中:
before(loaduser);
…
function loadUser () { User.findById(req.params.user_id, function (err, user) { if (err || !user) { redirect(path_to.users); } else { // this is where we make the actual user object accessible inside the view templating this.user = user; next(); } }.bind(this)); }
在你的setup / form.jade中:
- form_for( setup, { method: 'POST', action: path_to.user_setups(user) }, function(form){ //layout your form - });
看看文件app/views/setups/new.ejs
:
<h1>New setup</h1> <% form_for(setup, {action: path_to.setups, method: 'POST', id: "setup_form"}, function (form) { %> <%- partial('setups/form.ejs', {locals: {form: form, setup: setup}}) %> <%- form.submit('Create setup') %> or <%- link_to('Cancel', path_to.setups) %> <% });%>
它指的是不存在的pathpath_to.setups,您必须将其更改为正确的pathpath_to.user_setups:
<h1>New setup</h1> <% form_for(setup, {action: path_to.user_setups(user), method: 'POST', id: "setup_form"}, function (form) { %> <%- partial('setups/form.ejs', {locals: {form: form, setup: setup}}) %> <%- form.submit('Create setup') %> or <%- link_to('Cancel', path_to.setups) %> <% });%>
所以,你将POST到/users/…/setups而不是POST到/users/…/setups/new。
请注意,你需要传递用户作为path_to helper的第一个参数,所以铁路将为你build立正确的路线。