Rails路由更有意义

时间:2015-08-20 13:19:39

标签: ruby-on-rails routes

我有一个控制器,可以从ajax请求创建用户关系。控制器需要知道两个用户是谁以及什么类型的关系(父子,配偶等)。

我目前的路线是:

put 'relationships/:id/:second_id/:type'
get 'relationships/:id/:second_id/:type'
patch 'relationships/:id/:second_id/:type'
delete 'relationships/:id/:second_id/:type'

我的方法:create, show, update, delete

我的问题是,我可以制作一个do块来写这个更简洁吗?另外,这是最好的方法吗?

这是我到目前为止所做的:

resources :users do
    resources :family_relationships, :only => [:create, :update, :delete, :show], path: 'relationships', as: :relationships
  end

给了我这些路线:

      user_relationships POST   /users/:user_id/relationships(.:format)     family_relationships#create
       user_relationship GET    /users/:user_id/relationships/:id(.:format) family_relationships#show
                         PATCH  /users/:user_id/relationships/:id(.:format) family_relationships#update
                         PUT    /users/:user_id/relationships/:id(.:format) family_relationships#update

2 个答案:

答案 0 :(得分:0)

您可以在config/routes.rb中执行资源。它也可以像 -

那样嵌套
resources :relationships do 
  resources :types
end

如果你rake routes,它将导致路线可用

app_root>$ rake routes 

答案 1 :(得分:0)

这就是我想出来的(虽然我不相信没有更好的方法):

resources :users do
    put 'relationships/:uid/:type', controller: :family_relationships, action: :create
    get 'relationships/:uid/:type', controller: :family_relationships, action: :show
    patch 'relationships/:uid/:type', controller: :family_relationships, action: :update
    delete 'relationships/:uid/:type', controller: :family_relationships, action: :delete
  end

提供如下路线:

PUT    /users/:user_id/relationships/:uid/:type(.:format) family_relationships#create
GET    /users/:user_id/relationships/:uid/:type(.:format) family_relationships#show
PATCH  /users/:user_id/relationships/:uid/:type(.:format) family_relationships#update
DELETE /users/:user_id/relationships/:uid/:type(.:format) family_relationships#delete