オプションのパラメーターと制約を使用して、ルートをより有効に活用しようとしています! しかし、うまくいかないようです!
ゴール
(/: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
しかし、この方法では、セクションのないパスはまったく認識されません! 皆さんどう思いますか?ルートをきれいにするには、どちらに目を向ければよいですか?