【问题标题】:How to define 2 routes to seperate 2 categories of 1 object in Ruby on Rails 5.2?如何在 Ruby on Rails 5.2 中定义 2 条路由来分隔 2 个类别的 1 个对象?
【发布时间】:2020-03-10 15:43:16
【问题描述】:

我的应用程序管理业务对象。我有 2 类业务对象:

  1. “模板”业务对象
  2. “已实现”的业务对象

它们是相同的,但“已实现”类别成员始终引用“模板”,并且在编辑视图中具有一些显示为只读的字段。所以我只有 1 个班级和 1 个控制器。 “is_template”标志标记模板业务对象。

现在一项新要求要求在路由级别将这两个类别分开。在一条路线上,只能管理“模板”业务对象,在另一条路线上,可以管理“实施”业务对象。两者都通过同一个控制器。我尝试了以下方法,但不知道如何处理:

  resources :business_objects, :path => "template_metadata" do
    resources :skills       # Attributes of a business object
    member do
      post :new_version     # Manage some flags for templates
      post :make_current
      post :finalise
    end
    collection do
      get :index_used      # Former way to list only implemented business objects
    end
  end

  resources :implemented_objects, controller: 'business_objects' do
    resources :skills       # Attributes of a business object
  end

感谢您的帮助!

【问题讨论】:

  • 您能解释一下您遇到了什么样的问题吗?因为现在我觉得还不够解决

标签: ruby-on-rails routes


【解决方案1】:

您似乎需要在路由中添加一个额外的参数,以便您可以检查控制器中的对象类型。如果您使用命名参数将路由包装在范围内,它可以将其传递给您的控制器。 例如,

scope ":type", constraints: { :type => /(template|implemented)/ } do
  resources :business_objects, :path => "template_metadata" do
    resources :skills       # Attributes of a business object
    member do
      post :new_version     # Manage some flags for templates
      post :make_current
      post :finalise
    end
    collection do
      get :index_used      # Former way to list only implemented business objects
    end
  end

  resources :implemented_objects, controller: 'business_objects' do
    resources :skills       # Attributes of a business object
  end
end

将强制所有这些路由以type 为前缀,您将能够在控制器中访问params[:type]constraints: { :type => /(template|implemented)/ } 部分确保唯一的类型是 templateimplemented

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多