Routing nested resources in Rails 3

后端 未结 5 615
無奈伤痛
無奈伤痛 2020-12-07 20:51

I have a pretty common case for nested routes, I feel like, that looks something like this (in some sort of pseudonotation):

\'/:username/photos\' => Show         


        
相关标签:
5条回答
  • 2020-12-07 21:17

    The best way to do this depends on the application, but in my case it is certainly Option B. Using namespaced routes I'm able to use a module to keep different concerns separated out into different controllers in a very clean way. I'm also using a namespace-specific controller to add shared functionality to all controllers in a particular namespace (adding, for example, a before_filter to check for authentication and permission for all resources in the namespace).

    0 讨论(0)
  • 2020-12-07 21:19

    I did something similar to this in one of my apps. You're on the right track. What I did was declare nested resources, and build the query using the flexible arel-based syntax of Active Record in Rails 3. In your case it might look something like this:

    # config/routes.rb
    resources :photos, :only => :index
    resources :users do
      resources :photos
    end
    
    # app/controllers/photos_controller.rb
    def index
      @photos = Photo.scoped
      @photos = @photos.by_user(params[:user_id]) if params[:user_id]
      # ...
    end
    
    0 讨论(0)
  • 2020-12-07 21:20
    Example::Application.routes.draw do
      resources :accounts, :path => '' do
        resources :projects, :path => '', :except => [:index]
      end
    end
    

    Got the example from: http://jasoncodes.com/posts/rails-3-nested-resource-slugs

    Just applied that in my current project.

    0 讨论(0)
  • 2020-12-07 21:26

    You could define a seperate route for getting the photos for one user like so:

    get '(:username)/photos', :to => 'photos#index'
    

    But I would advise just using the nested resource that Jimmy posted above since that is the most flexible solution.

    0 讨论(0)
  • 2020-12-07 21:32

    Have you considered using a shallow nested route in this case?

    Shallow Route Nesting At times, nested resources can produce cumbersome URLs. A solution to this is to use shallow route nesting:

    resources :products, :shallow => true do
      resources :reviews
    end
    

    This will enable the recognition of the following routes:

    /products/1 => product_path(1)
    /products/1/reviews => product_reviews_index_path(1)
    /reviews/2 => reviews_path(2)
    
    0 讨论(0)
提交回复
热议问题