2012-04-13 48 views
2

也许我是愚蠢的,但Rails提供了生成的URL像这样这个漂亮的语法:传:新的Rails url_for

url_for([user, comment]) # => /users/1/comment/1 

传递:edit允许我创建这样的事情:

url_for([:edit, user, comment]) # => /users/1/comment/1/edit 

但是有什么方法可以跟踪?

url_for([:new, user, comments]) # => NoMethodError: undefined method `new_user_comments_url' 

UPDATE:增加了更多的信息。

我的routes.rb:

resources :users do 
    resources :comments 
end 

resources :posts do 
    resources :comments 
end 

我在这里的问题是,我不能使用Rails的自动生成的URL帮手(user_comments_url),因为我分享观点既为用户的意见和交注释。

有两种解决方法(但没有人感觉就像“导轨”三通),用于我的问题:

  1. 添加逻辑视图,例如一些条件。

  2. 定义我自己的网址助手,如new_parent_comment(user_or_blog)

回答

4

好了,找到了解决办法,但我不知道这是预期一个:

url_for([:new, user, :comment]) # => '/users/1/comments/new' 

url_for([:new, post, :comment]) # => '/posts/1/comments/new' 
2

根据Rails Docs url_for使用传递的对象的类名来生成RESTful路由。它还指出,对于嵌套路由,它不能正确地作出此假设:

如果您有嵌套路由,例如admin_workshop_path,则必须明确调用该路由(url_for无法猜测该路由)。

我建议在这里使用命名的路线,如new_user_comment_path()。我假设你已经设定了您的routes.rb这样的:

resources :users do 
    resources :comments do 
    end 
end 

此外,您可以运行rake routes打印出适当的名称为您的所有路线。 希望这会有所帮助, /Salernost

+0

增加了更多信息。 – 2012-04-13 21:07:49

0

难道这只是一个错字吗?我认为最后一行应改为comment,不comments:(假设你的comment变量定义)

url_for([:new, user, comment]) 

+0

不幸的是没有错别字,调用它会返回'''/ users/1/comments/new/1''''(如果注释已经存在)或者导致我的问题中提到的错误。 – 2012-04-13 21:07:23