【问题标题】:Nested routing in Ruby on RailsRuby on Rails 中的嵌套路由
【发布时间】:2010-04-01 08:30:32
【问题描述】:

我的模型类是:

class Category < ActiveRecord::Base
  acts_as_nested_set
  has_many :children, :foreign_key => "parent_id", :class_name => 'Category'
  belongs_to :parent, :foreign_key => "parent_id", :class_name => 'Category' 


  def to_param
    slug
  end
end

是否有可能有这样的递归路线: /root_category_slug/child_category_slug/child_of_a_child_category_slug ...等等

感谢您的帮助:)

【问题讨论】:

    标签: ruby-on-rails ruby routing nested-sets


    【解决方案1】:

    您可以通过常规路线和Route Globbing 做到这一点,例如,

    map.connect 'categories/*slugs', :controller => 'categories', :action => 'show_deeply_nested_category'
    

    然后在你的控制器中

    def show_deeply_nested_category
      do_something = params[:slugs]  # contains an array of the path segments
    end
    

    但是,请注意 nested resource routing 不建议超过一级深度。

    【讨论】:

    • 我也有同样的问题,而且效果很好。我认为 Jamis 的规则不适用于这种情况,因为资源本身被表示为层次结构。 (在这种情况下,无论如何都不需要使用嵌套资源/路由)。
    • 我不得不使用 'match' 而不是 'map.connect' 并且效果很好
    • 应该做些什么来替代嵌套不止一层?文档没有说。
    【解决方案2】:

    我对此表示怀疑,这不是一个好主意。 Rails Route 映射代码足够复杂,无需动态尝试编码和解码(可能)无限的路由字符串。

    【讨论】:

      【解决方案3】:

      您可以在 Rails 路由中使用约束。例如:

      match '*id', :to => 'categories#show', :constraints => TaxonConstraint.new
      
      class TaxonConstraint
        def matches?(request)
          path = request.path.slice(1..(request.path.length-1)
          path = path.split('/')
          return false if path.length != path.uniq.length
          return true if Category.check(path.last).first
          false
        end
      end
      

      class 用 "/" 分割你的路径,并检查 db 中的最后一个元素。如果未找到,则跳过该路线。 如果有人知道如何更好地解决它,将很高兴听到。

      【讨论】:

      • 嘿,我找到了最好的解决方案。然后使用acts_as_nested_set 创建新类别,您可以在1 个查询中生成root 路径。然后只需检查字段“路径”=>“a/b/c”。
      【解决方案4】:

      这并不容易(阅读:我不知道该怎么做)并且不建议这样做。想象一下,如果您有 10 个类别,您不希望 url 是 /categorya/categoryb/categoryc/categoryd/categorye/categoryf/categoryg/categoryh/categoryi/categoryj

      也许最高级别 3 会授予您所需的权力,而不会污染 URL?

      【讨论】:

      • 我认为级别应该受模型限制,而不是路由规则。
      • @Ryan Bigg,假设您确实有 n 深度,您希望如何为这样的内容编写 URL?他试图在树中的某个位置显示一个类别(它可能还有其他)。
      猜你喜欢
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 2014-06-23
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      相关资源
      最近更新 更多