【问题标题】:Rails slug for ancestry model用于祖先模型的 Rails slug
【发布时间】:2011-10-04 09:31:43
【问题描述】:

我的类别模型有血统。我使用蛞蝓宝石。 目前我有以下:

class Category < ActiveRecord::Base
  slug :name
end


class CategoriesController < ApplicationController
  inherit_resources
  defaults :finder => :find_by_slug
  def show
    @category = Category.find_by_slug(params['category_id'])
    show!
  end
end

  match "categories/:category_id" => 'categories#show', :as => :category

这很好用,但我想显示 parent/children 路径而不是 /children

如果我的类别有父级。如何达到这个目标?

例如,我将 BMW 类别和 x5 作为子类别。 我现在有这个链接:/categories/bmw 用于 bmw,/categories/x5 用于 x5。我需要这个链接categories/bmw/x5 而不是子类别

【问题讨论】:

    标签: ruby-on-rails routing tree slug


    【解决方案1】:

    您可以像这样将matchstatement 嵌套在您的父资源中(至少在Rails 3 中):

    resources :things do
      match "categories/:category_id" => 'categories#show', :as => :category
    end
    

    这应该创建一个类似/things/:thing_id/categories/:category_id的路由

    【讨论】:

    • 我不需要东西,我需要 categories/category/:subcategorycategories/category if parent
    【解决方案2】:
    match "categories/:category_id" => 'categories#show', :as => :category_short
    match "categories/:category/:category_id" => 'categories#show', :as => :category_long
    
      def category_path(category)
        unless category.is_root?
          category_long_path category.parent, category
        else
          category_short_path category
        end
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      相关资源
      最近更新 更多