Altonymous
Altonymous

Reputation: 783

Rails 3 - Nested Resources & Members/Collections

Is there a way to avoid having to do this...

resources :parents do
  resources :children do
    collection do
      get "/search/:term/:offset/:limit.:format", :action => "search", :constraints => { :term => /\w+/, :offset => /\d+/, :limit => /\d+/ }
    end
  end
end

resources :children do
  collection do
    get "/search/:term/:offset/:limit.:format", :action => "search", :constraints => { :term => /\w+/, :offset => /\d+/, :limit => /\d+/ }
  end
end

I thought it would be possible to just do this...

resources :parents do
  resources :children do
end

resources :children do
  collection do
    get "/search/:term/:offset/:limit.:format", :action => "search", :constraints => { :term => /\w+/, :offset => /\d+/, :limit => /\d+/ }
  end
end

The reason being is I want to be able to use both of these routes...

/children/search/term/0/10
/parents/1/children/search/term/0/10

Upvotes: 0

Views: 1273

Answers (1)

Paweł Obrok
Paweł Obrok

Reputation: 23194

This seems to do the trick

def define_children 
  resources :children do
    collection do
      get :search
    end
  end
end

define_children
resources :parents do
  define_children
end

:parent_id will be set in params if the route through parent has been used. Otherwise it won't be present. I have omitted constraints for clarity. Also you probably should make the .format optional.

Upvotes: 2

Related Questions