如何在Rails中构造以下JSONAPI URL?

时间:2015-07-05 17:00:57

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

我跟随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操作。

3 个答案:

答案 0 :(得分:2)

路线应该类似于以下代码段:

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

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

答案 1 :(得分: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

答案 2 :(得分:0)

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

我得到了它的工作:

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

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