0

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

路线:

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

产品.rb:

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

1 回答 1

0

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

尝试这个:

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

这会将产品捕获:id为中间带有斜线的任何东西,因此/products/abc/xyz/details将路由到products#detailswith params[:id]equal to 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
于 2013-11-02T21:12:14.830 回答