Rails 3:用于显示已过滤列表的路径设计

时间:2012-07-11 07:17:13

标签: ruby-on-rails-3 routes

我有两个资源:commentscommunities,每条评论都与一个或多个社区相关联。

我的计划是让网址/comments显示所有评论,/comments/:community_name仅显示来自特定社区的评论。 URL应该路由到`comments#index'动作,以从Comment模型中检索一组注释(使用named scope)。

如何生成这些路线? (或者如果有更合适的路线设计,请告诉我。)

如果我尝试下面的嵌套路线,似乎我需要提供评论ID,即\comment\:comment_id\communities\:community_id

#routes.rb
resources :comments, only: [:index, :create, :destroy]
resources :communities, only: [:index, :new, :create, :destroy]
resources :comments do
  resources :communities
end

注意:社区资源必须是独立资源,因为我需要查看,添加和删除社区的操作。

2 个答案:

答案 0 :(得分:0)

取消注释#routes.rb中的以下代码行并进行检查:
match ':controller(/:action(/:id))(.:format)'

答案 1 :(得分:0)

resources :comments, only: [:index, :create, :destroy] do
  collection do
    resources :communities, only: [:index, :new, :create, :destroy]
  end
end

此路线声明将为您提供以下网址:

comments/communities
comments/community/1, etc

如果您想使用社区名称作为社区ID,并且您希望为大多数资源执行此操作,那么最好为您的资源使用像friendly_id这样的好宝石。

相关问题