我有一个现有的基于搜索的应用程序正在移植到 Rails。由于遗留性质,我需要保留以下形式的现有 URL:
/books # search all books
/books/fiction # search books with :category => fiction
我将这些映射到我的 Controller 的 index
和 show
操作,它工作正常,但是用于显示所有书籍的代码和标记与特定类别的书籍书籍几乎完全相同。
组合 show
和 index
操作的最佳方式是什么?对于这个应用程序,index
实际上是 show
和 :category => nil
的退化情况。
我能做到:
def index
show
render "show"
end
但这看起来有点丑陋。在 Rails 中是否有更惯用的方法来执行此操作?
最佳答案
为什么不简单地使用一个带有可选类别的路由:
get '/books(/:category)' => 'books#search'
然后在 BooksController
中:
def search
# Look at params[:category], if it is there then use it
# to search, if it isn't there then list 'em all.
@results = ...
end
然后你只有一条路线、一个 Controller 、一个 View (控制它们并在黑暗中绑定(bind)它们)并且没有重复或欺骗。
关于ruby-on-rails - rails 路由 : combine index and show actions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10867633/