【问题标题】:How to define restfull routes to seperate 2 categories of 1 class with Rails 5.2?如何使用 Rails 5.2 定义 2 个类别的 1 个类别的休息路线?
【发布时间】:2020-05-07 14:28:24
【问题描述】:

我已经研究过这个主题,但只找到了部分解决方案。这里更好地解释了这个问题:

我管理 2 类业务对象:

  1. 定义的业务对象,可以认为是模板(有一个标志is_template=true)
  2. 使用的业务对象,是以前的副本,已实现,有细微差别

我对路由有 3 个期望:

  1. 依赖辅助工具,例如 used_business_objects_path 或 new_defined_business_object_path

  2. 显示用户友好的 URL,例如 /used_metadata/new(metatada 是我的客户要求显示的名称,而不是 Business Object)

  3. 传播控制器使用的类型变量

我想为这些人构建一个资源丰富的路线,包括控制器的参数,他应该选择哪种类型的对象:

  # GET /business_objects
  # GET /business_objects.json
  def index
    if params[:type] == 'defined'
      @business_objects = BusinessObject.joins(translated_objects).pgnd(current_playground).defined.visible.search(params[:criteria]).
      select(index_fields).order(order_by).paginate(page: params[:page], :per_page => paginate_lines)
    else
      @business_objects = BusinessObject.joins(translated_objects).pgnd(current_playground).used.visible.search(params[:criteria]).
        select(index_fields).order(order_by).paginate(page: params[:page], :per_page => paginate_lines)
    end

根据nick garrett 的建议,我实现了一个范围路由:

  scope :type, constraints: { :type => /(defined|used)/ } do
    resources :business_objects, :path => "#{:type}_metadata"  do
      resources :skills                   
      resources :skills_imports, :only=>[:new, :create]
      resources :scopes
      member do
        post :new_version
        post :make_current
        post :finalise
        post :activate
        post :open_cart     # Declares that the current business object collects skills as a cart
        post :close_cart    # Unsets the current business as cart
        get  :derive
      end
      collection do
        get :index_all
      end
    end
  end

不幸的是,这会生成一个 URL 为 /type/type_metadata?type=used 并且助手似乎不将类型视为参数。

阅读 Rails 路由指南后,我不确定我尝试实现的目标是否可行。您能帮忙找到解决方案吗? 非常感谢!

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    如果我正确理解您在此处尝试执行的操作,您可以使用routing concerns

    # have absolutely no clue what to name this
    concerns :business_object do
      resources :skills                   
      resources :skills_imports, only: [:new, :create]
      resources :scopes
      member do
        post :new_version
        post :make_current
        post :finalise
        post :activate
        post :open_cart     # Declares that the current business object collects skills as a cart
        post :close_cart    # Unsets the current business as cart
        get  :derive
      end
      collection do
        get :index_all
      end
    end
    
    resources :used_business_objects, concerns: :business_object 
    resources :defined_business_objects, concerns: :business_object
    

    我不会费心修补那个类型参数。只需使用继承并设置两个控制器类。

    【讨论】:

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