2015-04-04 101 views
0

我試圖在我的應用程序上實現搜索功能,我想知道什麼是最好的方法。Ruby模型搜索

我有一個具有2個布爾列(三,五)的玩家模型< - 列名稱 ,我試圖抓取它們用於可視化,具體取決於列是真還是假。 (顯示所有三個或全部五個)

我應該爲它們中的每一個創建控制器還是我應該在播放器控制器中定義它們?

至於模型,最好的方式來搜索它們會是這樣的?

players = Player.all 
players.find_by three: true 

還是有更優雅的方式?

+0

看看這個[RailsCast](http://railscasts.com/episodes/111-advanced-search-form)。 – MarsAtomic 2015-04-04 02:40:50

回答

1

如果您的情況變得更加複雜,請打開一個查詢對象。在此之前,這會讓你接近。然後在你的參數中,你所要做的就是將查詢設置爲'三'或'五'來獲得這種類型的球員。

class Player 
    scope :by_three -> where(three: true)} 
    scope :by_five -> where(five: true)} 
end 

def index 
    if params[:query] == 'three' 
    @players = Player.by_three 
    elsif params[:query] == 'five' 
    @players = Player.by_five 
    end 
end 
+0

我會試試看。 – Onilol 2015-04-04 04:00:01