Rails 3 - 嵌套资源&会员/收藏

时间:2011-09-09 02:01:12

标签: ruby-on-rails ruby-on-rails-3 routes dry

有没有办法避免不得不这样做......

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

我认为可以这样做......

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

原因是我希望能够使用这两种路线......

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

1 个答案:

答案 0 :(得分:2)

这似乎可以解决问题

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

define_children
resources :parents do
  define_children
end
如果已使用:parent_id的路线,则params将设置为parent。否则它将不存在。为清晰起见,我省略了约束。您也可以将.format设为可选。