Rails 4 [Best practices] Nested resources and shallow: true

后端 未结 5 1572
独厮守ぢ
独厮守ぢ 2020-12-28 15:44

The following post is based on Rails 4.

I am currently looking for a best-practice about the multiple nested resources (more than 1), and the option shallow: true.

5条回答
  •  天命终不由人
    2020-12-28 16:07

    I don't believe that Rails offers any built-in way to have the URLs use the full hierarchy (e.g. /projects/1/collections/2) but also have the shortcut helpers (e.g. collection_path instead of project_collection_path).

    If you really wanted to do this, you could roll out your own custom helper like the following:

    def collection_path(collection)
      # every collection record should have a reference to its parent project
      project_collection_path(collection.project, collection)
    end
    

    But that would be quite cumbersome to manually do for each resource.


    I think the idea behind the use of shallow routes is best summed up by the documentation:

    One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions. In other words, to only build routes with the minimal amount of information to uniquely identify the resource

    source: http://guides.rubyonrails.org/routing.html#shallow-nesting

    So while this may not be REST-compliant (as you say), you aren't losing any information because each resource can be uniquely identified and you are able to walk back up the hierarchy assuming your associations are set up properly.

提交回复
热议问题