2014-03-31 25 views
0

我在學習Rails,現在我對控制器有了很好的瞭解。順便說一句,我總是有一些問題,我不知道最好的解決方法是什麼。如何處理控制器中的其他參數

其中之一是搜索:我在我的網站搜索,我必須重新排序相關性和日期的結果。

我的搜索控制器

def show 
    @query = params[:query] 
    @contents = Content.published.search_by_text(@query).page(params[:page]).per(12) 
    end 

這是默認的搜索。我必須實施「數據訂單」搜索,我認爲要做這樣的事情:

def show 
    @query = params[:query] 
    @contents = Content.published.search_by_text(@query).page(params[:page]).per(12) 
    if params[:order] 
     @contents = Content.published.search_by_text(@query).reorder("created_at DESC").page(params[:page]).per(12) 
    end 
    end 

有沒有更好的方式來獲得我的結果?

回答

2

幸運的是,導軌讓我們可以調用鏈使用的Active Record(Rails的ORM)

這裏的時候是一種可能性:

def show 
    @query = params[:query] 
    @contents = Content.published.search_by_text(@query) 
    @contents = @contents.reorder("created_at DESC") if params[:order] 
    @contents = @contents.page(params[:page]).per(12) 
end 
相關問題