Rails 3, shallow routes

ぃ、小莉子 提交于 2019-12-03 12:50:31

You need to apply the :shallow option to the nested resources. This should give you what you want:

  resources :users do
    resources :recipe, :shallow=>true do
      resources :categories do
        resources :sections do
          resources :details do
          end
        end
      end
    end
  end  

If you look at the Rails 3 docs, you'll see that shallow is an instance method on ActionDispatch::Routing::Mapper::Resources, just like resource, resources, match, etc. You should be able to nest shallow routes with something like this:

shallow do
  resources :users do
    resources :recipe do
      resources :categories do
        resources :sections do
          resources :details
        end
      end
    end
  end
end

Though it only seems to expand them to 2 levels rather than the full nested route. Check out rake routes for more.

You can find Rails 3 documentation relating to nested or shallow routes on the Rails Guides site.

While offering advice on how to nest routes, it specifically says that, "Resources should never be nested more than 1 level deep."

It's reasonable that you only have new_user_recipe instead of new_recipe. Why? Because from the recipe's perspective, each and every recipe much belongs to a user.

Another point is that

resources :users, :shallow=>true do
  resources :recipe do
    resources :categories do
      resources :sections do
        resources :details do
        end
      end
    end
  end
end

is exactly the same as

resources :users do
  resources :recipe, :shallow=>true do
    resources :categories do
      resources :sections do
        resources :details do
        end
      end
    end
  end
end

:shallow is inherited as other users pointed out. Think about it, :shallow means you can omit the left part of the URL pattern once you are sure which exactly resource you are working on. If you put :shallow on the outer-most layer of your resource, it should have the same effect as you put it on the second layer (recipe in your example). Because you have nothing to omit when you are working on the outer-most resource (users in your example), it's already the left-most part of the URL pattern and it can't be omitted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!