新手问题 Couldn't find Post with id=new 错误

xautjzd · 2013年08月05日 · 最后由 Rei 回复于 2013年08月05日 · 2960 次阅读

我新建了一个名为 posts 的 controller,并且手动写的 CRUD,routes.rb 里面写的

get "/posts/:id", to: "posts#show", as: :post
get "/posts/new", to:"posts#new", as: :new_post
...

然后在 index 页面写的是: <%= link_to "Create", new_post_path %> 结果每次点“Create”时都出现 Couldn't find Post with id=new 错误,路由貌似判断错了,以为 new 是 show 的一个参数,所以跳转到了 show,而不是 new 的 action。请问这个怎么解决呢

详细错误:

ActiveRecord::RecordNotFound in PostsController#show

Couldn't find Post with id=new

def show
      @post = Post.find(params[:id])
end

Parameters:

{"id"=>"new"}

两条路由定义顺序换一下

#1 楼 @yesmeck 谢谢,换了下就行,能简单解释下原因么?

跟你另外一个帖子一样的原因啊。。。。

"/posts/:id" 包含了 "/posts/new"

路由从上到下匹配,匹配到了就进去 action,不管下面的路由。

楼主应该改用 resources 路由。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号