0

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

我的计划是让 URL/comments显示所有评论,并且/comments/:community_name只显示来自给定社区的评论。URL 应该路由到 `comments#index' 操作以从 Comment 模型中检索评论集(使用命名范围)。

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

如果我尝试下面的嵌套路由,似乎我需要提供评论 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

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

4

2 回答 2

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

此路由声明将为您提供如下 URL:

comments/communities
comments/community/1, etc

如果您想使用 community-name 作为社区 id,并且您希望对大部分资源都这样做,那么最好为您的资源使用像friendly_id这样的漂亮 gem 。

于 2012-07-12T02:36:32.197 回答
0

Uncomment the following line of code in #routes.rb and check it:
match ':controller(/:action(/:id))(.:format)'

于 2012-07-11T10:34:56.850 回答