【问题标题】:Rails routing URL folders for product categories on show actionsRails 路由显示操作上产品类别的 URL 文件夹
【发布时间】:2013-09-07 18:34:20
【问题描述】:

我正在尝试为我拥有的“产品”模型制定一些更好的网址,仅在展示操作中。我目前正在使用friend_id 来生成漂亮的蛞蝓,这很好,但如果可以的话,我正在尝试改进URL 流。

目前我的路径是这样的

    example.com/products/pretty-url-slug

在保存特定产品(到产品模型)时,我还保存了 type_of 属性。可以是android、iphone、windows

所以我试图最终拥有像这样的强大 URL

    example.com/products/iphone/pretty-url-slug

问题是,我没有或不相信我想要一个真正的“iphone”、“android”等控制器。但我宁愿只更新路线组合并显示正确处理此问题的操作。

到目前为止,我已尝试通过在路线上使用全部捕获来解决此问题,但无法正常工作。有什么建议或不同的方式来优雅地处理这个问题吗?

           routes

           resources :products

           # at the bottom of my routes a catch all
           match '*products' => 'products#show'

           # match routes for later time to do something with to act like a  
           # normal category page. 
           match 'products/iphone' => 'products#iphone_index'
           match 'products/android' => 'products#android_index'
           match 'products/windows' => 'products#windows_index'

           show action in the products controller

               def show
                # try to locate the product
                 if params[:product].present?
                  slug_to_lookup = params[:product].split("/").last
                  type_of  = params[:product].split("/").second
                  @product = Product.find_by_slug(slug_to_lookup)
                else
                  @product = Product.find_by_slug(params[:id])
                end


               # redirect if url is not the slug value
               if @product.blank?
                redirect_to dashboard_path
              elsif request.path != product_path(@product)
                redirect_to product_path(@product)
              end
             end

这种处理问题的方法很有效,但我无法弄清楚如何附加 type_of 属性并生成有效的 URL。

【问题讨论】:

    标签: ruby-on-rails url routing routes


    【解决方案1】:

    像这样定义你的路线怎么样:

    获取 ':controller/:action/:id/:user_id'

    在这里,除了 :controller 或 :action 之外的任何东西都可以作为参数的一部分用于操作。

    【讨论】:

      【解决方案2】:

      感谢您的建议。当我仔细考虑时,我实际上能够解决这个问题并且非常简单。这可能对其他人有帮助。

      在我的路线中,我刚刚为我拥有的每种类别创建了一条路线。所以每次一个新的类别,我都需要添加一个额外的路线,例如:

          # match for each product category
          match 'shop/iphone/:slug' => 'products#show', :as => :product_iphone
          match 'shop/android/:slug' => 'products#show', :as => :product_android
          match 'shop/windows/:slug' => 'products#show', :as => :product_windows
      

      然后在产品的展示操作中而不是指导中,如果 slug 与现有产品匹配,您只需渲染产品/展示

         @product = Product.find_by_slug(params[:slug])
      

      然后在您的视图中,您可以链接到这样的特定类别

         link_to "product", product_android_path(@product)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-28
        • 1970-01-01
        • 2018-06-14
        • 2019-04-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多