【问题标题】:Rails - How to add a route to some resourcesRails - 如何向某些资源添加路由
【发布时间】:2015-11-21 05:28:41
【问题描述】:

某些路由用于 CRUD 操作,例如客户端、电话号码和产品。我对许多模型都有“唯一索引”属性。例如,在客户端中,我可以有“电子邮件”或“用户名”,而在产品中我可以有“序列号”,而在电话号码中,实际的“号码”可以是唯一索引。

所以,我的 ApplicationController 中有一些方法可以在 POST 请求中接收 JSON,其中包含属性名称和属性值。服务器检查值是否存在并通知用户输入是否有效或值是否存在。

所以,对于这些模型,我必须声明一个指向“唯一”方法的路由,如下所示

routes.rb

resources :clients
resources :phone_numbers
resources :products
post 'clients/unique' => 'clients#unique'
post 'phone_numbers/unique' => 'phone_numbers#unique'
post 'products/unique' => 'products#unique'

我的问题是:我可以“分组”这些路由,不带前缀(与 namespacescope 不同),只为它们添加 post 'unique' 吗?伪代码是这样的

伪代码

group alias: 'modelsWithUniqueAttrs'
    resources :clients
    resources :phone_numbers
    resources :products

    add_route 'unique'
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    试试这个

    resources :clients, :phone_numbers, :products do
      collection do
        post :unique
      end
    end
    

    或者

    unique_routing = Proc.new do
      collection do
        post :unique
      end
    end
    resources :clients, &unique_routing
    resources :phone_numbers, &unique_routing
    resources :products, &unique_routing
    

    或者

    unique_routing = Proc.new do
      collection do
        post :unique
      end
    end
    resources :clients, :phone_numbers, :products, &unique_routing
    

    【讨论】:

      【解决方案2】:

      你可以这样定义你的路线:

      resources :clients do
        member do
          post :unique => 'clients#unique'
        end
      end
      
      resources :phone_numbers do
        member do
          post :unique => 'phone_numbers#unique'
        end
      end
      
      resources :products do
        member do
          post :unique => 'products#unique'
        end
      end
      

      这些将为您提供如下路线:

      unique_client           POST     /clients/:id/unique(.:format)                clients#unique
      unique_phone_numbers    POST     /phone_numbers/:id/unique(.:format)          phone_numbers#unique
      unique_products         POST     /products/:id/unique(.:format)               products#unique
      

      更新

      您可以像这样使用集合块定义路由:

        resources :clients, only: [:uniq] do
          collection do
            post :uniq
          end
        end
      

      你给你的路线如下:

      uniq_clients POST /clients/uniq(.:format) clients#uniq
      

      但是,这仍然不是您想要的。因为,productsphone_numbers 也必须有类似的收集块。

      【讨论】:

      • 不幸的是,我不使用 /clients/:id/unique。我使用 /clients/unique,并传递一个 JSON,例如 {attrName: 'email', attrValue: 'test@test.com'}。我想要一个不需要我为每个控制器编写 'controller_name#unique' 的解决方案......相反,我想将它们分组以一次向所有控制器添加 'unique'
      • 添加一个collection 块,参见herehere
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      相关资源
      最近更新 更多