繁体   English   中英

Ruby on Rails中的嵌套路由

[英]Nested routing in Ruby on Rails

我的模型类是:

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 ...等等

感谢您的任何帮助 :)

您可以使用常规路线和路线全球化进行此操作,例如,

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

但请注意,不建议深度超过一级的嵌套资源路由

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

您可以在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以查找db中的最后一个元素。 如果没有找到,请跳过该路线。 如果有人知道,如何更好地解决它,将很高兴听到。

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

最高等级3可能会给你所需的力量,而不会污染URL?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM