【问题标题】:Rails 3 Routes: Override Topics#show with Posts#indexRails 3 路线:覆盖主题#show with Posts#index
【发布时间】:2011-08-10 10:03:43
【问题描述】:

非常简单的问题,但我似乎无法弄清楚如何做到这一点,即使在搜索了 Rails 路由指南之后。

假设主题有嵌套的资源帖子。

主题的帖子都列在 Posts#index (/topics/:topic_id/messages) 中。 Topics#show 没有任何用途。我希望在请求 /topics/:topic_id 时检索 Posts#index,而不必在主题控制器中粘贴重定向。

谢谢!

更新

我能够得到想要的结果:

routes.rb

match 'forums/:forum_id' => 'topics#index', :as => 'forum_topics', :via => :get
match 'topics/:topic_id' => 'messages#index', :as => 'topic_messages', :via => :get

resources :forums, :shallow => true, :except => :show do
  resources :topics, :shallow => true, :except => :show do
    resources :messages
  end
end

但是,我不确定这是否是最好的方法。

更新 2 我上面的方法打破了其他 CRUD 方法(如#create)。仍在寻找将 /messages 排除在 url 之外的解决方案。

【问题讨论】:

  • 您的路线文件看起来如何?
  • 查看我的更新。我解决了这个问题,但仍然想知道是否有更好的解决方案。

标签: ruby-on-rails routing


【解决方案1】:

添加这条路线

get "/topics/:topic_id" => redirect("/topics/%{topic_id}/messages")

UPD

没有重定向:

get "/topics/:id" => "topic::Messages#index"

或者,如果您使用的是shallow

get "/topics/:id" => "messages#index"

resources :forums, :shallow => true, :except => :show do
  resources :topics, :shallow => true, :except => :show do
    resources :messages
  end
end

【讨论】:

  • 谢谢。我实际上希望根本不会看到 /messages,因为它是不必要的 URL 信息。
  • 使用这个:get '/topics/:topic_id' => 'messages#index 确实允许我正在寻找的路径,但我希望这个路径(/topics/:topic_id)在使用路由助手时是默认的:topic_messages_path(@topic) for例子。添加:as => 'topic_messages' 完成了此操作,但随后中断了其他 CRUD 请求。
  • 顺便说一句,我接受了你的回答,因为你确实回答了我提出的问题,现在我只是在扩展它。
  • 你可以在这里使用:as => 'topic_messages',它不应该破坏其他方法,因为它只是关于GET
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
  • 2011-08-29
  • 2020-09-24
  • 2018-03-25
  • 1970-01-01
相关资源
最近更新 更多