2017-05-07 19 views
0

我需要的控制器檢查,如果在一個表中存在一個字符串,然後返回「真」或「假」,這樣我可以if語句中使用它。 例如,如果字符串「羅伯特」,在「my_friends」表存在,我需要顯示從另一個名爲表與「羅伯特」的相應項目「好時」。如何,如果在表中存在串返回true,Ruby on Rails的

我意識到.exists不會在這個應用程序的工作,因爲我在尋找一個字符串。

@my_friends.where(friend_id: 'Robert').exists? #always returns false 
    @goodtimes = goodtime.where friend_id: "Robert" #works 

的僞代碼是這樣的:提前

if (table x contains string "Robert") 
    @goodtimes = goodtime.where friend_id: "Robert" #display goodtimes from table y 

謝謝, 戴夫

+0

您要搜索該字符串表中的每一列? – Gerry

+0

不,只是friend_id列。 friend_id列在兩個表中。 –

+0

使用您的模型並定期進行AR查詢,您想要查詢的表的模型是什麼? – Gerry

回答

0

您可以檢查羅伯特是否存在使用.where().present

if @my_friends.where(:friend_id => 'Robert').present? 
    # Robert exists 
else 
    # Robert doesn't exist 
end 

有關更多方法,請參見this answer檢查記錄是否存在。

+0

謝謝shambalambala! –

相關問題