【问题标题】:How to construct the following JSONAPI url in Rails?如何在 Rails 中构造以下 JSONAPI url?
【发布时间】:2015-09-22 19:57:06
【问题描述】:

我关注http://jsonapi.org/format/#document-top-level

我注意到以下终点(路线):

/articles/1/relationships/author

在 Rails 中,routes.rb 中如何构造这条路由?

resources :articles do
  # What goes here?
  # Should relationship be a namespace or other?
  # I guess author can be defined as a collection, or just a simple get
end

relationships 不需要 7 个 RESTFUL 操作中的任何一个。

【问题讨论】:

  • 取决于,您是否还有许多其他资源可以归入/relationships ?您的关联控制器(子文件夹?)在哪里,您的控制器操作是什么?
  • 可能不会,所以我猜namespace :relationships do; get 'author'; end; 应该没问题。这也意味着get 'author' 路由将指向ArticlesController 中的author 操作。除非有办法让author 操作存在于Relationships 控制器中吗?我认为这有助于更好的逻辑抽象
  • 也许值得研究一下您是否可以使用 routing concerns,因为在 API 的上下文中,您可以将其用于许多其他资源

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


【解决方案1】:

路由应该像下面的代码sn-ps:

resources :articles do
   resources :relationships, :only => [] do
     collection do 
       get :author
     end
   end
end

这就是路由文件的样子。如果需要任何更新,请告诉我。

【讨论】:

  • 我进行了编辑,因此relationships 路由不充当资源(即没有索引、显示等)。并为其显式指定一个控制器,使其位于articles 文件夹中
  • 对不起,我没有清楚地得到您的评论。你能更准确地解释你的问题吗?
  • 您最初的答案是正确的。只是一些建议。只需指定 resources :relationships 将公开 relationships 的 7 个 RESTFUL 操作(索引、显示、新建、更新等)。如果没有controller: 'articles/relationships'author 操作将存在于relationships#author 而不是articles/relationships#author。只是觉得我应该指出这一点
  • 好吧,这样关系就不需要暴露任何安宁的动作了吧?
  • 是的,让我更新我最初的问题以明确这一点
【解决方案2】:

根据我的担忧,您可能必须在多个资源中使用它(rails doc is quite well-written

concern :has_author do
  scope '/relationships' do
    resource :author
  end
end

resources :articles, concerns :has_author

相当于

resources :articles do
  scope :'/relationships' do
    resource :author
  end
end

【讨论】:

    【解决方案3】:

    scope :'/relationships' 对我不起作用(至少在 Rails 5 中)。

    我得到了它的工作:

    resources :articles do
      resources :author, path: 'relationships/author'
    end
    

    这将只使用AuthorController 并将其映射到/articles/:id/relationships/author

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      相关资源
      最近更新 更多