2012-06-25 46 views

回答

2

他們都產生相同的SQL語句:

1.9.3p194 :003 > Example.find_by_id(9) 
    Example Load (0.3ms) SELECT "examples".* FROM "examples" WHERE "examples"."id" = 9 LIMIT 1 
nil 
1.9.3p194 :004 > Example.where(:id => 9).first 
    Example Load (0.3ms) SELECT "examples".* FROM "examples" WHERE "examples"."id" = 9 LIMIT 1 
nil 

那麼他們就必須在數據庫相同的性能特點。在Rails代碼中,find_by_*_where可能會有細微的差別,但我認爲與查詢時間相比,這個值可以忽略不計。


編輯:Ryan Bigg's comment below光,我不得不建議向前兼容的第二種形式。

+0

我相信,如果它不能找到subject_id這個方法返回一個錯誤出,而我看到的2個選項返回零。更新我的問題以澄清。 – Nick5a1

+0

我已經更新了我的答案。 – Brandan

+5

對於(更新的)記錄:Rails 4並沒有棄用'find_by_id':http://edgeguides.rubyonrails.org/4_0_release_notes.html#active-record-deprecations –

5

我喜歡find_by_id的名稱是描述性的,你會得到的物體不必調用第二功能(即first

User.find(9)    # returns User object. Throws exception when not found.  
User.find_by_id(9)  # returns User object. Returns nil when not found.  
User.where(:id=>9).first # returns User object. Returns nil when not found. 
相關問題