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

前端 未结 4 1277
走了就别回头了
走了就别回头了 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:34

    I often like to separate those actions. When the resulting actions are very similar you can separate the scopes inside the controller easy by seeing if params[:category_id] is present etc (see @SimoneCarletti answer).

    Normally separating actions in the controller by using custom routes gives you most flexibility and clear results. Following code results in normal route helper names but the routes are directed to specific actions in controller.

    In routes.rb:

    resources categories do
      resources articles, :except => [:index] do
        get :index, :on => :collection, :action => 'index_articles'
      end
    end
    resources articles, :except => [:index] do
      get :index, :on => :collection, :action => 'index_all'
    end
    

    Then you can have in ArticlesController.rb

    def index_all
      @articles = @articles = Articles.all
      render :index # or something else
    end
    
    def index_categories
      @articles = Articles.find_by_category_id(params[:category_id])
      render :index # or something else
    end
    

提交回复
热议问题