【发布时间】:2018-07-09 03:16:07
【问题描述】:
我正在使用 gem Ancestry,并尝试构建我的路线以显示父母和孩子之间的层次结构。
Location.rb
def to_param
if self.ancestors?
get_location_slug(parent_id) + "/" + "#{slug}"
else
"#{slug}"
end
end
def get_location_slug(location_id)
location = Location.find(location_id)
"#{location.slug}"
end
这 99% 完美运行,并且清晰地显示了我的路线 - 但它在我的路线中显示“%2F”而不是“/”:
localhost:3000/locations/location-1 (perfect)
localhost:3000/locations/location-1%2Flocation-2 (not quite perfect)
Routes.rb(共享以防万一)
match 'locations/:id' => 'locations#show', :as => :location, :via => :get
match 'locations/:parent_id/:id' => 'locations#show', as: :location_child, via: :get
额外问题:这目前涵盖 root 位置和 child 位置。我如何将其扩展到 孙子 位置和 曾孙 位置?提前致谢!
【问题讨论】:
-
match 'locations/:id/:id'我很惊讶它甚至被解析器接受了。我认为您的路线设置不正确。 -
@JoshBrody 我认为你是对的,它看起来很奇怪。我假设我应该用 :parent_id 替换第一个 :id,但我不确定如果有另一个级别该怎么办。例如,您知道 :grandparent_id 是否有效吗?
-
你的路线应该是RESTful
-
您需要再通过guides.rubyonrails.org/routing.html 一次。您将弄清楚嵌套路由是如何创建的。
-
您是否尝试过将您的路线声明为
/.../*slug? Rails 尝试积极地参数化所有内容,以便无论您在标识符中输入什么内容,它都能在 URL 中正常工作,而/是保留字符。
标签: ruby-on-rails ruby routes ruby-on-rails-5 ancestry