【发布时间】:2011-12-07 06:30:25
【问题描述】:
我现在这个问题已经被问了一千次了,但这对我没有帮助,呵呵 :) 我已经过了一个小时了。我的表格:
= form_for @comment, :url_for => { :action => "create", :controller => "comments"}, :method => :post
我的 rake 路线:
POST /t/:trunk_id/r/:root_id/comments(.:format) {:action=>"create", :controller=>"comments"}
trunk_root_comment GET /t/:trunk_id/r/:root_id/comments/:id(.:format) {:action=>"show", :controller=>"comments"}
错误:
undefined method `comments_path' for #<#<Class:0x007fed2c713128>:0x007fed2c71cc78>
如果我将表单命名为:
= form_for [:trunk_root, @comment], :url_for => { :action => "create", :controller => "comments"}, :method => :post do |f|
这应该使路由trunk_root_cmets_path..根据rake路由是正确的..我得到:
No route matches {:controller=>"comments", :format=>nil}
非常感谢您的帮助.. 已经看了好几个小时了..
更新:
感谢 Ryan 提供了这么好的答案!对我只是“扔东西”的东西的一个非常清楚的解释,现在至少我理解得更好了。实际上,我的 rake 路由中已经有 'trunk_root_cmets_path' 可用,并且我尝试了你提到的几种组合,但我并没有真正了解我所缺少的东西,所以你提供了帮助。我正在使用 Mongo,实际上我没有 Trunk 模型,我只有一个名为 @root.trunk 的根属性,尽管我有一个 Trunk 控制器,因此它是我路由的一部分(可能是个坏主意 idk) .
所以我尝试了你的 TLDR,它说错误:
Undefined method 'root_comments_path'
.. 因为不存在 Trunk 模型,我假设?.. 所以我让 @trunk 与
的正确 id 相等= form_for [@trunk, @root, @comment] do |f|
= form_for @comment, :url => (trunk_root_comments_path(:trunk_id => @root.trunk, :root_id => @root.id)) do |f|
果然行得通...所以我不太确定如何缩短它...对我来说奇怪的是我在路线中具有相同深度的另一个嵌套资源“照片”我能够让它与 = form_for [:trunk_root, @photo], :html => { :class=> 'root_form' } do |f|.. 但由于某种原因我不能..无论如何,我会说你给了我足够的理解 100% 但我认为我从 20% 理解到 50% 理解.. 我现在知道 id 对路由很重要,并且命名的助手需要访问它们。我介绍了 url_helper 的工作原理,但我认为需要阅读更多内容才能真正完全理解它。我现在也能够以更长的形式构建适当的路线,至少可以通过这种棘手的情况。所以谢谢你:)
【问题讨论】:
-
忽略我的回答(至少暂时 :))您的路线是如何设置的?
标签: ruby-on-rails-3 routing ruby-on-rails-3.1