简体   繁体   English

rails - 创建类似路线的最佳实践?

[英]rails - Best practice for creating similar routes?

In my application, a User can make a Post, and a User can make Correction (think of it as a comment) on another user's post.在我的应用程序中,用户可以发布帖子,用户可以对另一个用户的帖子进行更正(将其视为评论)。 Each User can have many Posts, and each Post can have many Corrections.每个用户可以有很多帖子,每个帖子可以有很多更正。

On each show page for a Post, there is a form to create a new Correction.在帖子的每个显示页面上,都有一个用于创建新更正的表单。 This uses the user_post_corrections path.这使用user_post_corrections路径。

On the show page for each User, I would like to display each Correction they've submitted for any Post.在每个用户的显示页面上,我想显示他们为任何帖子提交的每个更正。 This requires a user_corrections path.这需要一个user_corrections路径。

In order to achieve this, I have the following in my routes.rb:为了实现这一点,我在 routes.rb 中有以下内容:

resources :users do
    resources :posts do
      resources :corrections
      end
    end

    resources :users do
      resources :corrections
    end

This intuitively feels bad to me, as I've created two nested routes that are very similar to one another.这对我来说直觉上感觉不好,因为我创建了两个彼此非常相似的嵌套路由。

Is there a better way to do this?有一个更好的方法吗? My code is working fine as it is but is there a best practice method for implementing this kind of model?我的代码运行良好,但是否有实现这种模型的最佳实践方法?

Routing concerns are an excellent but underused tool for DRYing out your routes: 路由问题是一个很好但未被充分利用的工具,用于干燥你的路由:

concern :correctable do
  resources :corrections
end

# just an example of multiple concerns
concern :commentable do
  resources :comments
end

resources :users, concerns: :correctable
resources :posts, concerns: [:correctable, :commentable]

However you should take when creating nested routes so that you are not nesting needlessly.但是,您应该在创建嵌套路由时使用,以免不必要地嵌套。

Often you might want the collective actions [new, index, create] to be scoped by the parent:通常,您可能希望集体操作[new, index, create]由父级限定范围:

GET|POST  /posts/:post_id/corrections
GET       /posts/:post_id/corrections/new

While you want the member actions to be unscoped since you can always access a record directly if it has a unique id.虽然您希望成员操作没有作用域,因为如果记录具有唯一 id,您始终可以直接访问该记录。

GET    /corrections/:id
GET    /corrections/:id/edit
PATCH  /corrections/:id
DELETE /corrections/:id

To do this you would declare the routes like so:为此,您可以像这样声明路线:

resources :corrections, only: [:show, :update, :edit]

concern :correctable do
  resources :corrections, only: [:new, :index, :create]
end

resources :users, :posts, concerns: [:correctable]

The shallow: true option does something like this but does not work well when you declare the same resources several times as it adds unscoped routes for every call. shallow: true选项做这样的事情,但当你多次声明相同的resources时,它不能很好地工作,因为它为每次调用添加了无作用域的路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM