1

我正在尝试通过可选参数和约束更好地使用我的路线!但这似乎不起作用!

目标

我的目标是使以下路径起作用 (/: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 这样的路线以及路线文件中的所有其他路线都可以正常工作。

切断重复

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

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

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

4

0 回答 0