2016-11-04 18 views
0

我有一個查詢雲:的Rails /主動Record-如何使用「取」,如果有任何匹配的記錄

ModalType.where(id: modal['modal_id']).take.template 

的問題是,我可能會在運行的情況下當查詢沒有找到任何ID:莫代爾[ 'modal_id'],然後我得到的錯誤

undefined method `template' for nil:NilClass 

我怎麼能寫的東西會 '採取' 只有在這裏BUT(ID:modal_id)返回的東西(=發現)?

+1

邊注:這似乎更加聲明: 'ModalType.find_by(id:modal ['modal_id'])' – tokland

回答

3

使用Ruby < 2.3:

object = ModalType.where(id: modal['modal_id']).take 
if object 
    object.template 
else 
    # I don't know. it's up to you 
end 

ModalType.where(id: modal['modal_id']).take.try(:template) 

使用Ruby> = 2.3,你可以使用安全導航操作:

template = ModalType.where(id: modal['modal_id']).take&.template 
+0

謝謝,我應該提到我使用紅寶石2.3 :) – Mathieu

+0

不知道這個「安全導航」,它是超級有用 – Mathieu

+0

這是一個新的說法'.try(:template)'的方式' – Dan

相關問題