【问题标题】:Ignore part of the path in Rails 3忽略 Rails 3 中的部分路径
【发布时间】:2013-11-02 15:38:31
【问题描述】:

我希望能够忽略我的应用程序中的部分路径。 例如: example.com/products/toys/big-toy,应该通过忽略“玩具”部分(只是产品/大玩具)来路由。我知道路线中可用的通配符,但它忽略了产品路径之后的所有内容。我不知道如何做到这一点并保持我的嵌套资源正常工作。

路线:

resources :products do
  member do
    match :details
  end
  resources :photos
end

product.rb:

def to_param
  "#{category.slug}/#{slug}"
end

【问题讨论】:

    标签: ruby-on-rails path routing wildcard


    【解决方案1】:

    解决这个问题的一种方法是使用路由约束。

    试试这个:

    resources :products, constraints: { id: /[^\/]+\/[^\/]+/ } do
        member do
          match :details, via: :get
        end
      resources :photos
    end
    

    这会将产品:id 捕获为中间带有斜线的任何内容,因此/products/abc/xyz/details 将路由到products#details,params[:id] 等于abc/xyz。

    然后,您可以在 ProductsController 中添加一个前置过滤器,如下所示:

    class ProductsController < ApplicationController
      before_filter :parse_id
    
      // ...
    
      def parse_id
        slugs = params[:id].split("/")
        params[:category_id] = slugs[0]
        params[:id] = slugs[1]
      end
    end
    

    【讨论】:

    • 嘿,感谢您的建议,但所有其他路线,如编辑、索引和嵌套资源,例如相片。 /products/toys/big-toy/photos 会起作用吗?
    • 对不起@StefanAdamov,我误解了你的问题。我已经更新了我的答案来做你想做的事(我认为)。
    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多