目标是创建以下 URL 路由:
localhost:3000/category-1/location-1/
localhost:3000/category-1/location-1/sub-location-2
localhost:3000/category-1/location-1/sub-location-2/sub-location-3
我有一系列已被分成几类的地点。每个位置可以属于1个类别,也可以属于1个位置,或者是一个根位置。
Category.rb
has_many :locations
Location.rb
belongs_to :category
has_ancestry
我考虑过将我的 Location 模型拆分为 Location 和 SubLocation,但它不够灵活,无法支持所有可能的位置。这将是理想的结构,但我不确定它是否会支持这样的路由。
理想情况下,路由还支持通过 gem Friendly_Id 使用 slug,但目前这些仅适用于类别模型。
我该怎么做才能让我的路线像这样工作?
最佳答案
get ':category/:location', to: 'locations#action1'
get ':category/:location/:sublocation', to: 'locations#action2'
get ':category/:location/:sublocation/:subsublocation', to: 'locations#action3'
参见 Rails Routing from the Outside In了解更多信息
关于ruby-on-rails - Rails - 自连接祖先,可能有嵌套路线和 slug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51236676/