嵌套路由on Rails的
我的模型类:嵌套路由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
...等一个
感谢您的帮助: )
你可以做到这一点与定期航线和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的规则不适用于这种情况,因为资源本身被表示为一个等级结构。 (无论如何,在这种情况下不需要使用嵌套资源/路由)。 – 2010-05-21 19:47:27
我不得不使用“匹配”而不是“map.connect”,它的工作很完美 – 2013-12-11 11:23:01
作为嵌套多个深层的替代方案,应该做些什么?该文件没有说。 – 0112 2014-08-12 21:29:10
这不容易(阅读:我不知道该怎么做),并不建议。想象一下,如果你有10个类别,你不希望url为/categorya/categoryb/categoryc/categoryd/categorye/categoryf/categoryg/categoryh/categoryi/categoryj
。
也许*别3会授予您所需的权力,而不污染URL?
对于我的意见级别,该级别应该受模型限制,而不受路由规则的限制。 – vooD 2010-04-03 12:44:37
@Ryan Bigg,假设你有深度的话,你会如何为这样的东西写一个URL?他试图在树中的某个位置显示一个类别(并且可能有其他类别)。 – 2010-04-04 02:32:48
我怀疑它,这不是一个好主意。 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的最后一个元素。如果找不到,则跳过路线。 如果有人知道,如何更好地解决它,会很高兴听到。
嘿,我找到了最好的解决方案。然后使用acts_as_nested_set创建新类别,您可以在1个查询中生成根路径。然后只检查字段“路径”=>“a/b/c”。 – SpX 2011-08-03 10:48:08
伟大的问题。 – 2010-04-04 02:30:40