改善我的路线加入/退出

时间:2012-03-09 18:25:37

标签: ruby-on-rails rest refactoring routes

我有很多加入/离开路线,我怎么能改进我写这个的方式? 或者我可以让它成为RESTful吗?

  match 'events/:id/join' => 'events#join', :as => 'join_event'
  match 'events/:id/disjoin' => 'events#disjoin', :as => 'disjoin_event'

  match 'assos/:id/join' => 'assos#join', :as => 'join_asso'
  match 'assos/:id/disjoin' => 'assos#disjoin', :as => 'disjoin_asso'

  match 'projects/:id/join' => 'projects#join', :as => 'join_project'
  match 'projects/:id/disjoin' => 'projects#disjoin', :as => 'disjoin_project'

  match 'roles/:id/join' => 'roles#join', :as => 'join_role'
  match 'roles/:id/disjoin/:user_id' => 'roles#disjoin', :as => 'disjoin_role'

  match 'groups/:id/join' => 'groups#join', :as => 'join_group'
  match 'groups/:id/disjoin/:user_id' => 'groups#disjoin', :as => 'disjoin_group'

1 个答案:

答案 0 :(得分:1)

此路由似乎不是RESTful的原因是因为您要根据操作组织事物,而不是资源。当您为应用程序设置RESTful路由时,请考虑您正在操作的资源,然后将自己限制为HTTP谓词为这些操作定义的核心操作。

举一个例子,表达“加入一个组”的一种方法可能是将membership资源作为该组的嵌套路由。然后,您可以对该资源执行不同的操作,例如POST 创建成员资格(加入组),DELETE 删除 a成员资格(“脱离”一个团体)。您的路线可以设置如下:

resources :events do
  resources :members, :only => [:create, :destroy]
end

然后,您可以通过POST /events/1/members拨打电话加入小组,然后将DELETE发送到/events/1/members/(membership_id)