Rails 3.2.13路由:可选参数约束路由的开始

时间:2013-07-01 10:39:33

标签: ruby-on-rails-3.2 routes constraints optional-parameters

我试图通过可选的参数和约束来更好地使用我的路线!但它似乎不起作用!

目标

我的目标是使以下路径有效 (/:section_id)/:post_type_id(/:year(/:month(/:day(/:id)))) 这样就可以在有或没有部分的情况下呈现帖子。

工作解决方案

我得到的临时解决方案是制作类似的重复路线:

section_constraints = lambda { |request| 
  Section.exists?(id: request.params[:section_id])
}
post_type_constraints = lambda { |request|
  PostType.exists?(id: request.params[:post_type_id])
}

scope ':section_id',:as=>'section', :constraints => section_constraints do
  root :to=>'posts#index'
  scope ':post_type_id',:as=>'post_type', :constraints => post_type_constraints do
    get '(/:year(/:month(/:day)))' => 'posts#index', :as=> :posts
    get '(/:year(/:month(/:day(/:id))))' => 'posts#show', :as => :post
  end
end

scope ':post_type_id',:as=>'post_type', :constraints => post_type_constraints do
  get '(/:year(/:month(/:day)))' => 'posts#index', :as=> :posts
  get '(/:year(/:month(/:day(/:id))))' => 'posts#show', :as => :post
end

所以我得到这样的路线:

/:section_id/:post_type_id(/:year(/:month(/:day)))
/:section_id/:post_type_id(/:year(/:month(/:day(/:id))))

/:post_type_id(/:year(/:month(/:day)))
/:post_type_id(/:year(/:month(/:day(/:id))))

路由文件中的/first_section_id/news和/ first_section_id以及所有其他路由工作正常。

BUT

切断重复

我想对可选参数进行约束!它应该是这样的:

scope '(/:section_id)', constraints: section_constraints  do
  scope '/:post_type_id', constraints: post_type_constraints do
    get '(/:year(/:month(/:day)))' => 'posts#index', :as=> :posts
    get '(/:year(/:month(/:day(/:id))))' => 'posts#show', :as => :post
  end
end

但这样它根本无法识别没有部分的路径!你们觉得怎么样?我应该以哪种方式让我的路线变得干净整洁?

0 个答案:

没有答案