Rails: Nested resources conflict, how to scope the index action depending on the called route

前端 未结 4 1349
走了就别回头了
走了就别回头了 2021-02-13 19:50

Imagine you have two defined routes:

map.resources articles
map.resources categories, :has_many => :articles

both accessible by helpers/path

4条回答
  •  不要未来只要你来
    2021-02-13 20:31

    Having only a single nested resource, using a conditional based on the params to determine it's scope would be the easiest approach. This is likely the way to go in your case.

    if params[:category_id]
      @articles = Category.find(params[:category_id]).articles
    else
      @articles = Article.all
    end
    

    However, depending on what other nested resources you have for the model, sticking with this approach can get quite tedious. In which case, using a plugin like resource_controller or make_resourceful will make this much simpler.

    class ArticlesController < ResourceController::Base
      belongs_to :category
    end
    

    This will actually do everything you'd expect. It gives you all your standard RESTful actions and will automatically setup the scope for /categories/1/articles.

提交回复
热议问题