Rails Namespace vs. Nested Resource

前端 未结 2 2020
一向
一向 2021-01-30 15:21

Let\'s say my app has two models, Foo and Bar.

Foo optionally belongs_to Bar.

Right now I can look at a single Foo, or search for a particular Foo, and the FoosC

2条回答
  •  一个人的身影
    2021-01-30 15:35

    There are cons to this approach.

    If you declare a constant, eg. CONST_NAME, in nested resource foos, rails will throw "uninitialized constant ::Foo::CONST_NAME" exception because of its scope algorithm.

    To avoid such behaviour, use:

    resources :foos
    resources :bars do
      scope :module => "bar" do
        resources :foos #, :controller => 'bar/foos' no need to use this now because route will be searched there by default
      end
    end
    

    Now you will not get an exception while using:

    Foo::CONST_NAME
    

    or

    Bar::Foo::CONST_NAME
    

提交回复
热议问题