【问题标题】:Self nesting rails categories自嵌套导轨类别
【发布时间】:2014-07-22 13:01:39
【问题描述】:

我有一个商店应用程序,我需要在其中创建自定义路由系统,其中 URL 存储产品的类别。例如,http://example.com/languages/ruby/rails 将显示名为“rails”的类别#show,其父项名为“ruby”,其父项名为“languages”,http://example.com/languages/ruby/rails/store 的 URL 将显示此类别中的产品。
目前我有:
category.rb

belongs_to :parent, class_name: 'Category'
has_many :categories, foreign_key: :parent_id
has_many :products

routes.rb

resources :categories, :path => '', :only => [:index, :show] do
  resources :products, :path => '', :only => [:show]
end
root :to => 'products#index'

但它仍然最多可堆叠 2 个,例如URL http://example.comhttp://example.com/languages 显示类别/子类别列表,但 http://example.com/languages/ruby参数{"action"=>"show", "controller"=>"products", "category_id"=>"language", "id"=>"ruby"}
从路线中删除产品根本没有帮助 - 然后它只是说No route matches [GET] "/language/ruby",尽管我认为它可能会导致需要额外检查当前 URL 是否指向类别或产品。
我也尝试了get '*categories/:id', to: 'category#show' 变化 + 我正在使用friendly_id gem,所以路径看起来不像http://example.com/2/54/111/6
我只是想找出这种情况下最好的 ruby​​ on rails 解决方案,当您需要搜索引擎优化 + 无止境(例如,无法定义这种递归可以走多深)嵌套自己的嵌套资源时(包括事实category/language/category/ruby/category/rails 看起来很丑)。

注意:我使用的大部分信息来自 Stack Overflow 和 railscasts.com(包括 pro/revised 剧集),因此提及具有此类信息的良好来源也会很棒。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 routing friendly-id


    【解决方案1】:

    我最近使用我最近在 Rails 上构建的 CMS 自己解决了这个问题。我基本上在运行时从数据库记录中动态构建路由。我写了这篇关于策略的博文:

    http://codeconnoisseur.org/ramblings/creating-dynamic-routes-at-runtime-in-rails-4

    解决方案的核心(改编上面的博客文章)只是简单地遍历数据库记录并构造每个类别所需的路由。这是执行此操作的主要类:

    class DynamicRouter
      def self.load
        Website::Application.routes.draw do
    
          Category.all.each do |cat|
            get cat.route, 
              to: "categories#show", 
              defaults: { id: cat.id }, 
              as: "#{cat.routeable_name}_#{cat.name}"
          end
        end
      end
    
      def self.reload
        Website::Application.routes_reloader.reload!
      end
    end
    

    对于上述情况,Category 模型应该实现一个“routeable_name”方法,它简单地给出类别名称的下划线版本,该名称唯一地命名该类别的路由(它不是绝对必要的,但在执行“rake routes”时有助于查看什么你有)。 #route 方法构造到该类别的完整路径。请注意为类别设置 ID 参数的默认值。这使得控制器操作可以非常简单地查找类别的 ID 字段,如下所示:

    class CategoryController < ApplicationController
      def show
        @category = Category.find(params[:id])
      end
    end
    

    【讨论】:

    • 这是一个聪明的解决方案!您能更好地解释一下您所说的 routeable_name 是什么意思吗?
    • routeable_name 就是您希望在 URL 中反映出来的内容。例如“/categories/ruby-on-rails”与“/categories/rubyonrails”。
    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2014-03-11
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多