3

我有一个现有的基于搜索的应用程序正在移植到 Rails。由于遗留性质,我需要保留表单的现有 URL:

/books          # search all books
/books/fiction  # search books with :category => fiction

我将这些映射到我的控制器的index&show操作,它工作正常,但是用于显示所有书籍与特定类别书籍的代码和标记几乎相同。

show结合和index动作的最佳方式是什么?因为这个应用程序index确实是showwith的退化案例:category => nil

我可以:

def index
   show
   render "show"
end

但这似乎有点难看。在 Rails 中是否有更惯用的方法来做到这一点?

4

1 回答 1

4

为什么不简单地使用带有可选类别的一条路线:

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

然后你只有一条路线,一个控制器,一个视图(统治它们并在黑暗中约束它们),没有重复或诡计。

于 2012-06-03T03:27:31.827 回答