Rails中的动态自定义路由

时间:2015-05-21 16:41:53

标签: ruby-on-rails

我不想使用Rails路由约定,因为我希望我的网址看起来像某种方式。我的模型结构层次结构是动态的。

如果我有这三条路径引用不同的书籍:

/book/chapter/page

/book/chapter/page/sentence

/book/page/sentence

我存储在DB(mongodb)中的不同书籍具有不同的层次结构,但它们都以书本开头,而句子结束时,它只是中间部分的变化。

我目前的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"}

1 个答案:

答案 0 :(得分:1)

我知道您不想使用默认路由,但您可以使它们正常工作。

scope ':bookName' do
  scope '(:chapter)', :chapter => /c\d+/ do #we need to know if it's a chapter
    scope '(:page)', :page => /p\d+/ do #or a page, c1 = chapter, p1 = page
      resources :sentence
    end
    resources :page
  end
  resources :chapter
end

()使路径的一部分可选。