Ruby on rails RubyonRails中的嵌套路由
我的模范班是:Ruby on rails RubyonRails中的嵌套路由,ruby-on-rails,ruby,routing,nested-sets,Ruby On Rails,Ruby,Routing,Nested Sets,我的模范班是: 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_para
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
类别“父项id”,:类名称=>“类别”
属于\u to:parent,:foreign\u key=>“parent\u id”,:class\u name=>“Category”
def至_参数
鼻涕虫
结束
结束
有没有可能有这样的递归路由:
/root\u category\u slug/child\u category\u slug/child\u of a\u child\u category\u slug
。。。还有一个
谢谢你的帮助:)这不容易(阅读:我不知道怎么做),也不建议这样做。假设您有10个类别,您不希望url是/categorya/categoryb/categoryc/categoryd/categorye/categoryf/categoryg/categoryh/categoryi/categoryj
也许最高级别为3可以在不污染URL的情况下授予您所需的权限 我对此表示怀疑,这不是一个好主意。Rails路由映射代码非常复杂,无需动态尝试编码和解码(可能)无限的路由字符串。您可以使用常规路由进行编码,例如
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路由中使用约束。例如:
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
类将路径拆分为“/”,并检查db中的最后一个元素。如果未找到,则跳过该路线。
如果有人知道如何更好地解决它,我会很高兴听到。我认为级别应该受到模型的限制,而不是路由规则的限制。@Ryan Bigg,假设您有n-depth,您希望如何为类似的内容编写URL?他试图在树中的某个位置显示一个类别(可能还有其他类别)。我也有同样的问题,这非常有效。我认为Jamis的规则不适用于这种情况,因为资源本身被表示为一个层次结构。(在这种情况下,没有必要使用嵌套的资源/路由)。我必须使用“匹配”而不是“map.connect”,而且它工作得很好。除了嵌套多个深度之外,应该做什么呢?文档没有说。嘿,我找到了最好的解决方案。然后使用acts_作为_嵌套_集创建新类别,您可以在1个查询中生成根目录的路径。然后只需检查字段“路径”=>“a/b/c”。