rails routing:组合索引和显示操作

时间:2012-06-03 03:18:19

标签: ruby-on-rails rails-routing

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

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

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

结合showindex行动的最佳方式是什么?对于此应用,index实际上是show :category => nil的堕落情况。

我能做到:

def index
   show
   render "show"
end

但这看起来很难看。在Rails中有更惯用的方法吗?

1 个答案:

答案 0 :(得分: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

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

相关问题