【发布时间】:2015-05-22 01:35:42
【问题描述】:
我不想使用 Rails 路由约定,因为我希望我的网址看起来像某种方式。我的模型结构层次是动态的。
如果我有这三个路径引用不同的书:
/book/chapter/page
/book/chapter/page/sentence
/book/page/sentence
我存储在数据库 (mongodb) 中的不同书籍具有不同的层次结构,但它们都以 Book 开头并以 Sentence 结尾,只是中间部分有所不同。
我目前对 Routes 的逻辑是在 RoutesController 中处理这一切:
路线
get '*path', to: "routes#route"
路线#路线
def route
path = params[:path].split("/")
## Look up the book
book = Book.find_by(name: path[0])
## Get the book specific hierarchy, like ["books", "pages", "sentences"]
## or ["books", "chapters", "pages", "sentences"]
hierarchy = book.hierarchy
if path.length == hierarchy.length
## Since end of hierarchy is always sentence
## Here is want to redirect_to Sentence#Show
else
## Here I want to look up based on model specific hierarchy
## LOOKUP CONTROLLER: hierarchy[path.length-1]}", ACTION: Show
## eg: Chapter#show, Subchapter#show, Page#show, etc.
end
end
我不能做一个简单的 redirect_to 因为我没有使用 config/routes 文件所以它会抛出一个错误:
No route matches {:action=>"show", :controller=>"chapters", :path=>"books/chapters"}
【问题讨论】:
-
你的模型是什么?它们之间有什么关系?
标签: ruby-on-rails