2017-03-15 52 views
1

我想要獲得第一個其中active=1並返回一個json。空數組在GET .json與`哪裏'

# GET /banners.json 
def index 
    @banners = Banner.where(active: '1').first 
end 

這是返回一個空數組[]。 如果我改變並做Banner.All正確返回所有數據

回答

2

這與數據有關,而不是與代碼有關。顯然,你沒有任何橫幅active等於1。如果有的話,Rails誠實地爲你回報它。比這

更好,你可以在Banner模型像這樣創建範圍:

scope :active, -> { where(active: 1) } 

而在你的控制器,你可以調用它像以下:

def index 
    @banners = Banner.active.first 
end