RESTfully Nesting Resource Routes with Single Identifiers

前端 未结 4 1951
情话喂你
情话喂你 2021-02-06 04:47

In my Rails app I have a fairly standard has_many relationship between two entities. A Foo has zero or more Bars; a Bar belongs to exactly

4条回答
  •  故里飘歌
    2021-02-06 05:16

    Personally, if each Bar is dependent on a Foo, option #2 makes more sense. For example, if Foo is a blog and Bar is a post, it is far more logical to access a particular post at example.bloghosting.com/blog/1/post/2 than example.bloghosting.com/post/21.

    Do do this with the latest version of Rails:

    class Food < ActiveRecord::Base
        has_many :bars
    end
    
    class Bar < ActiveRecord::Base
        belongs_to :foo
    end
    

    Then, in the Rails router (/config/routes.rb):

    map.resources :foos do |foo|
        foo.resource :bars
    end
    

    For more information, see Rails Routing from the Outside In and the Rails API Documentation.

提交回复
热议问题